简体   繁体   English

找不到变量:token

[英]Can't find variable: token

Im trying to get data from an endpoint API with axios but there is this error: Cant find token, can you please help me??我正在尝试使用 axios 从端点 API 获取数据,但出现此错误:找不到令牌,您能帮帮我吗? This is my code, the first file is request and the second file is the code where im trying to get data.这是我的代码,第一个文件是请求,第二个文件是我试图获取数据的代码。

request file:请求文件:

import axios from "axios"

let axiosApiInstance = axios.create();

function setToken(token,RefreshToken) {
    
    axios.defaults.headers.common['x-access-token'] = token;

    axiosApiInstance.interceptors.response.use((response) => {
        return response
      }, async function (error) {
        const originalRequest = error.config;
        if (error.response.status === 401 && !originalRequest._retry) {
          originalRequest._retry = true;           
          axios.defaults.headers.common['x-refresh-token'] = RefreshToken;
          return axiosApiInstance(originalRequest);
        }
        return Promise.reject(error);
      });
   
}

export default {
    get: axios.get,
    post: axios.post,
    delete: axios.delete,
    put: axios.put,
    setToken: setToken,
}

this is the code im using to get data in a screen这是我用来在屏幕上获取数据的代码

useEffect(() => {
    getData();
    return () => {};
  }, []);

  const getData = async () => {
    request
      .get("http://18.156.84.96:5000/api/client/orders/get-orders/1/Active", {
        headers: {
          Authorization: `${token}`,
        },
      })
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
        console.error(error);
      });
  };

Modify setToken function to set token in the following way:修改setToken function,设置token如下:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    config.headers.Authorization =  token;

    return config;
});

And remove headers objects from the get request, as token isn't available here并从 get 请求中删除 headers 对象,因为令牌在此处不可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM