Hema Ramasamy
Hema Ramasamy

Reputation: 726

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

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()
    ])
}

Upvotes: 3

Views: 13885

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

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.

Upvotes: 9

Related Questions