AxiosError {message: 'Network Error'} 当我为登录表单制作 axios.post 时

问题描述 投票:0回答:2

我使用 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;

接下来创建自定义挂钩,用于在调度中保存 paylod 的 accessToken 和用户数据:

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 };
};

完成后,我从表单处理程序中调用此函数:

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

我为我的端点(针对登录用户)执行的所有这些操作。当我使用邮递员作为此端点 http://localhost:9000/api/admin/login 时,一切正常,但是当我将其连接到前端部分时,我得到了

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

我还制作了 console.log("The config from $api.interceptors.request:", config) 和 config.headers.Authorization 为 Bearer null

我该如何解决这个问题,或者我可能错过了什么。非常感谢你

javascript reactjs node.js axios interceptor
2个回答
0
投票

您使用什么浏览器?如果您使用的是 Firefox,请尝试转到 about:config 页面并尝试更改一些设置。具体来说,将

network.fetch.redirect.stripAuthHeader
network.http.redirect.stripAuthHeader
设置为
false

或者,您可以将标头名称从“授权”更改为“令牌”

参考: Github 问题


0
投票

您需要在 axios 拦截器中跳过登录请求“/admin/login”的授权标头。

您的日志清楚地显示“config.headers.Authorization is Bearer null”,这意味着您的本地存储没有任何令牌。只有登录后您才会获得令牌。

© www.soinside.com 2019 - 2024. All rights reserved.