Axios baseURL is not appending with the URL in react.js

Viewed 3033

I had made the axios setup with saga.js, when the user clicks the Register button have to dispatch an action and it will hit the request, everything is working fine, except appending the baseURL in the url, the url http://users/register,

My axios setup,

 import axios from 'axios';

const axiosClient = axios.create({
    baseURL : `https://test-url.com/`
});


export function postRequest(URL, payload) {
    return axiosClient.post(`/${URL}`, payload).then(response => response);
}

saga.js

import { put, takeEvery, all, call } from 'redux-saga/effects';
import {register} from "./serviceWorker";
import { postRequest } from './helpers/axiosClient';
import actions from "./redux/actions";

function* registerUser(params) {
    try {
        const response = yield call(() => postRequest('/users/register', params.payload));
        console.log('response', response.data);
        yield put({
            type: actions.ON_REGISTER_SUCCESS,
            payload: response.data,
        });
    } catch (error) {}
}

function* watchIncrementAsync() {
    yield takeEvery('ON_REGISTER', registerUser)
}

export default function* rootSaga() {
    yield all([
        watchIncrementAsync()
    ])
}
1 Answers

If you remove the leading slash added to URL in postRequest, axios will use the base URL to build the full path.

return axiosClient.post(URL, payload).then(response => response);

If you would like to understand what's happening, this is where axios builds the full path. It thinks you're passing an absolute URL (since the path '//users/register' starts with a double slash) and doesn't use the base URL.

Related