如何使用 Axios 拦截器向响应添加一些 headers?

How can I use Axios interceptors to add some headers to responses?

在我的 Reactjs 应用程序中,我想添加一个拦截器,它可以将一些 headers 附加到一些后端响应

所以,我尝试了这个:

    export default function App() {
      axios.interceptors.response.use(
        (config)=> {
          config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
          return config;
        },
        (error) => {
          // ON ERREOR
        })
       ......
      );

我想我的 header 会附加在每个 back-end 响应中。但这似乎行不通。

建议??

试试这个:

    axios.interceptors.response.use(
      function (response) {
        const edited_response = response;
        edited_response.headers["custom_header"] = "test";
        return edited_response;
      },
      function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      }
    );

嘿,这是不起作用的原因,因为您正在调用使用方法来更新 repsonse headers 但能够要将 headers 发送到您的后端 API,您需要从 request object 调用 use 方法。方法如下:

axios.interceptors.request.use(
  function handleRequestInterceptor(config) {
    const modifiedConfig = {
      ...config,
      headers: {
        myheader: "myvalue",  <=== your custom headers like auth etc.
        ...config.headers,
      },
    };
    return modifiedConfig;
  },
  function handleRequestInterceptorError(error) {
    return Promise.reject(error);
  }
);

添加请求拦截器

axios.interceptors.request.use(
    config => {
        const token = localStorage.getItem('auth_token');
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        config.headers['Content-Type'] = 'application/json';
        return config;
    },
    error => {
        Promise.reject(error)
});

添加响应拦截器

axios.interceptors.response.use((response) => { // block to handle success case
    return response
 }, function (error) { // block to handle error case
    const originalRequest = error.config;
 
    if (error.response.status === 401 && originalRequest.url ===
 'http://dummydomain.com/auth/token') { // Added this condition to avoid infinite loop 

 
        // Redirect to any unauthorised route to avoid infinite loop...
        return Promise.reject(error);
    }
 
    if (error.response.status === 401 && !originalRequest._retry) { // Code inside this block will refresh the auth token
 
        originalRequest._retry = true;
        const refreshToken = 'xxxxxxxxxx'; // Write the  logic  or call here the function which is having the login to refresh the token.
        return axios.post('/auth/token',
            {
                "refresh_token": refreshToken
            })
            .then(res => {
                if (res.status === 201) {
                    localStorage.setItem('auth_token',res.data);
                    axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('auth_token');
                    return axios(originalRequest);
                }
            })
    }
    return Promise.reject(error);
});

Click here详细看题目