【问题标题】:How can I use Axios interceptors to add some headers to responses?如何使用 Axios 拦截器向响应添加一些标头?
【发布时间】:2021-10-13 06:28:57
【问题描述】:

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

所以,我尝试了这个:

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

我想我的标题会附加在每个后端响应中。但这似乎不起作用。

建议??

【问题讨论】:

    标签: javascript reactjs axios create-react-app


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      嘿,这不起作用的原因是因为您正在调用 use 方法来更新 repsonse 标头,但是为了能够将标头发送到您的后端 api,您需要调用使用来自 request 对象的方法。你可以这样做:

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

      【讨论】:

      • 我不想更新我的请求头,我想为我的后端响应添加一个头
      • @firasKoubaa 但你为什么要这样做?只是想知道用例
      • 我想为一些我不会更改代码的后端服务器添加 CORS 标头(已经部署的解决方案),所有这些都用于实验目的
      • @firasKoubaa 你想绕过 CORS 吗?
      【解决方案3】:

      添加请求拦截器

      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查看话题详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2020-10-22
        • 2015-11-13
        • 1970-01-01
        • 2016-01-02
        • 2023-01-21
        • 2020-09-25
        相关资源
        最近更新 更多