Attach Authorization header for all axios requests

前端 未结 9 1982
灰色年华
灰色年华 2020-12-04 05:17

I have a react/redux application that fetches a token from an api server. After the user authenticates I\'d like to make all axios requests have that token as an Authorizati

9条回答
  •  一向
    一向 (楼主)
    2020-12-04 05:30

    The point is to set the token on the interceptors for each request

    import axios from "axios";
        
    const httpClient = axios.create({
        baseURL: "http://youradress",
        // baseURL: process.env.APP_API_BASE_URL,
    });
    
    httpClient.interceptors.request.use(function (config) {
        const token = localStorage.getItem('token');
        config.headers.Authorization =  token ? `Bearer ${token}` : '';
        return config;
    });
    

提交回复
热议问题