我在cookie中设置token axios get token undefined直到我刷新页面

2vuwiymt  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(170)

这是我的axios文件

import axios from "axios";
import Cookies from "js-cookie";

const token = Cookies.get("token");

const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL, // Replace with your API base URL
  timeout: 10000, // Optional: Set a timeout for requests
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Content-Type": "application/json",
    ...(token && { "x-access-token": token }),
  },
});

export default api;

字符串
当我登录时,我在cookie中设置了tokentoken设置了,但axios直到我刷新页面才得到它。在页面刷新时,axios重新呈现,所以axios从cookie中获得了token

rjzwgtxy

rjzwgtxy1#

在加载代码时创建api示例时,仅从cookie读取一次令牌值。
使用request interceptor在发出请求时读取并注入当前令牌值。
范例:

import axios from "axios";
import Cookies from "js-cookie";

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_API_URL, // Replace with your API base URL
  timeout: 10000, // Optional: Set a timeout for requests
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Content-Type": "application/json",
  },
});

axiosInstance.interceptors.request.use(config => {
  const token = Cookies.get("token");

  if (token) {
    config.headers["x-access-token"] = token;
  }

  return config;
});

export default axiosInstance;

字符串

相关问题