Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    ])
}
like image 840
Hema Ramasamy Avatar asked Oct 19 '25 09:10

Hema Ramasamy


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.

like image 101
Arun Kumar Mohan Avatar answered Oct 20 '25 22:10

Arun Kumar Mohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!