【问题标题】:React - can't set headers with axiosReact - 无法使用 axios 设置标题
【发布时间】:2021-07-18 01:30:33
【问题描述】:

我目前正在制作快递 --> react api。我无法使用 jwt 令牌设置标题,我想我已经尝试了我能找到的任何方法。会不会和CORS设置有关?

Redux 操作

  return (dispatch) => {
    return instance.post("/login", userData).then((res) => {
      const token = res.data.accessToken;

      localStorage.setItem("token", token);

      instance.interceptors.request.use(
        (config) => {
          const token = localStorage.getItem("token");
          const auth = token ? `Bearer ${token}` : "";
          config.headers.common["Authorization"] = auth;
          return config;
        },
        (error) => Promise.reject(error)
      );

      // setAuthorizationToken(token);
    });
  };
};

令牌正确地落在本地存储中。

全局 axios 设置

var instance = axios.create({
  baseURL: "http://localhost:4000",
  withCredentials: true,
});

服务器端的 Cors 设置。

  app.use(
    cors({
      credentials: true,
      allowedHeaders: "Content-Type, Authorization",
      exposedHeaders: "Authorization",
      origin:
        process.env.NODE_ENV === "development"
          ? "http://localhost:3000"
          : (process.env.FRONTEND_HOST as string),
    })
  );

有什么想法吗?

【问题讨论】:

    标签: reactjs express redux axios http-headers


    【解决方案1】:

    如果是 CORS 问题,您可以在浏览器控制台中查看。 尝试这个。在你的全局 axios 设置中

    const instance = axios.create({
        baseURL: "http://localhost:4000",
        headers: {
            Authorization: `Bearer ` + localStorage.getItem("token"),
        },
        responseType: "json",
    });
    
    instance.interceptors.request.use(
        (config) => {
            const token = localStorage.getItem("token");
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
            return config;
        },
        (error) => {
            return Promise.reject(error);
        }
    );
    
    export default instance;
    

    Redux 操作

      return (dispatch) => {
        return instance.post("/login", userData).then((res) => {
          const token = res.data.accessToken;
          localStorage.setItem("token", token);
          
          // dispatch action here
          
        });
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 2021-07-20
      • 2019-06-15
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2018-02-26
      • 2020-12-24
      相关资源
      最近更新 更多