如何使用Axios拦截器为响应添加一些头信息?

3
在我的Reactjs应用程序中,我想添加一个拦截器,可以将一些头信息附加到某些后端响应中。因此,我尝试了以下代码:
    export default function App() {
      axios.interceptors.response.use(
        (config)=> {
          config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
          return config;
        },
        (error) => {
          // ON ERREOR
        })
       ......
      );

我想我的头部会被添加到每个后端响应中,但似乎并没有起作用。
有什么建议吗?
3个回答

8

添加请求拦截器

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);
});

点击这里查看详细内容。


2
嘿,之所以不起作用是因为您调用了use方法来更新响应头,但要能够将标头发送到后端API,您需要从请求对象调用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);
  }
);

我不想更新我的请求头,我想为我的后端响应添加一个头部。 - undefined
@firasKoubaa 但是为什么你想要这样做呢?只是想知道使用案例而已。 - undefined
我想为一些后端服务器添加CORS头,而不需要更改代码(已经部署的解决方案),这一切都是为了实验目的。 - undefined
@firasKoubaa 你是想绕过CORS吗? - undefined

0

试试这个:

    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);
      }
    );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接