AxiosError {message: 'Network Error' } while I make the axios.post for login form

102 Views Asked by At

I make the simple interceptors use axios:

import axios from "axios";

const $api = axios.create({
  withCredentials: true,
  baseURL: "http://localhost:9000/api",
});

$api.interceptors.request.use((config) => {
  config.headers.Authorization = `Bearer ${localStorage.getItem("accessToken")}`;
  console.log("The config from $api.interceptors.request:", config)
  return config;
});

export default $api;

Next create the custom hook for save accessToken and user data for paylod in dispatch:

import { useState } from "react";
import { useAutnContex } from "./useAuthContext";
import actions from "../../actions/AuthActions";
import $api from "../../http";

export const useLogin = () => {
  const [error, setError]: any = useState(null);
  const [isLoading, setIsLoading]: any = useState(null);
  const { dispatch }: any = useAutnContex();

  const login = async (email: string, password: string) => {
    setIsLoading(true);

    try {
      const response = await $api.post("/admin/login", { email, password });

      localStorage.setItem("accessToken", response.data.accessToken);
      localStorage.setItem("user", JSON.stringify(response.data.user));

      dispatch({
        type: actions.LOGIN,
        payload: response.data.user
      });

      setIsLoading(false);
    } catch (error) {
      setError(error);
      setIsLoading(false);
      console.log(error);
    }
  };
  return { login, isLoading, error };
};

and finish I call this function from my form handler:

  const handleSubmit = async (event: any) => {
    await login(form.values.email, form.values.password);
  };

all these actions I do for my endpoint ( for login user ). When I use postman for this endpoint http://localhost:9000/api/admin/login everythin is working, but when I connect it to front-end part I get

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…},      request: XMLHttpRequest, …} 

and also I make console.log("The config from $api.interceptors.request:", config) and config.headers.Authorization is Bearer null

How I can solve this problem or maybe I miss something. Thank you very much

2

There are 2 best solutions below

0
Phill On

What browser do you use? If you're using Firefox, try going to the about:config page and attempt to change some settings. Specifically, set network.fetch.redirect.stripAuthHeader and network.http.redirect.stripAuthHeader to false.
Alternatively, you can change the header name from 'Authorization' to 'Token

Reference: Github Issues

0
Sanjai Ramasamy On

You need to skip the Authorization header for login request "/admin/login" in axios interceptor.

Your logs says clearly "config.headers.Authorization is Bearer null" which means your local storage does not have any token. Only after login you will have the token.