Search code examples
reactjsaxios

My axios instance does not work and I do not know why


I have created a seperate axios.js file for an axios instance to make requests to an API I have running live. When I use the axios instance in my login route I get a POST http://127.0.0.1:3000/login 404 (Not Found) error, even though the url defined in my axios instance is not my localhost it is the url of the API. Now, when I use axios in my login route and enter the whole API url instead of using the instance, the POST request goes to the correct url and I get proper response. I do not understand this. Everything on the API is fine and has been tested many times AND I have used an axios instance like this before.

here is the instance I have set up(baseUrl is correct in my code):

import axios from 'axios';

const axiosInstance = axios.create({
  baseUrl: REMOVED,
  headers: {
    Authorization: localStorage.getItem('accessToken')
      ? 'Bearer ' + localStorage.getItem('accessToken')
      : null,
    'Content-Type': 'application/json',
  },
});

export default axiosInstance;

here is the login function that uses my axios instance and does not work:

export const login = (email, password) => (dispatch) => {
  axiosInstance
    .post('/login', { email: email, password: password })
    .then((res) => {
      dispatch({
        type: LOGIN_SUCCESS,
        payload: res.data,
      });
    })
    .catch((err) => {
      console.log(err);
      dispatch({
        type: LOGIN_FAIL,
      });
    });
};

here is the login function that works perfectly:

export const login = (email, password) => (dispatch) => {
  axios
    .post('fullurlnotshown/login', { email: email, password: password })
    .then((res) => {
      dispatch({
        type: LOGIN_SUCCESS,
        payload: res.data,
      });
    })
    .catch((err) => {
      console.log(err);
      dispatch({
        type: LOGIN_FAIL,
      });
    });
};

EDIT: SOLVED THE PROBLEM... 'baseUrl:' in the instance should be 'baseURL:'


Solution

  • You may be referencing the wrong property of baseUrl. The axios documentation has the property as baseURL (URL instead of Url).

    Axios is probably silently ignoring your incorrect property key and falling back to localhost.