4

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()
    ])
}
2
  • 2
    I had the problem when an instance method's relative path doesn't append to the base URL. The reason is that I used an incorrect config property name: baseUrl instead of baseURL. Commented Dec 30, 2022 at 19:23
  • Thank you soo much! I literally spent 1 hour thinking what's wrong in my code @MegaCasper Commented Mar 14, 2023 at 8:01

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.