且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为所有axios请求附加授权标头

更新时间:2021-07-07 06:00:24

有多种方法可以实现此目的.在这里,我解释了两种最常见的方法.

There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1.您可以使用 axios拦截器来拦截任何请求并添加授权标头.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    const token = store.getState().session.token;
    config.headers.Authorization =  token;

    return config;
});

2.从axios文档中,您可以看到有一种机制可以允许您可以设置默认标头,该标头将随您提出的每个请求一起发送.

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

所以在您的情况下:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

如果需要,您可以创建一个自执行函数,当令牌存在于商店中时,该函数将自行设置授权标头.

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {
     String token = store.getState().session.token;
     if (token) {
         axios.defaults.headers.common['Authorization'] = token;
     } else {
         axios.defaults.headers.common['Authorization'] = null;
         /*if setting null does not remove `Authorization` header then try     
           delete axios.defaults.headers.common['Authorization'];
         */
     }
})();

现在,您不再需要将令牌手动附加到每个请求.您可以将上述函数放置在每次都可以执行的文件中(例如包含路由的文件).

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

希望它会有所帮助:)