简体   繁体   中英

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?? 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:

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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