为所有axios请求附加授权标头 [英] Attach Authorization header for all axios requests

查看:160
本文介绍了为所有axios请求附加授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react/redux应用程序,该应用程序从api服务器获取令牌.用户验证之后,我想使所有axios请求都将该令牌作为Authorization标头,而不必手动将其附加到操作中的每个请求.我对React/Redux相当陌生,不确定是否采用最佳方法,也没有在Google上找到任何优质的搜索结果.

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 Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.

这是我的redux设置:

Here is my redux setup:

// actions.js
import axios from 'axios';

export function loginUser(props) {
  const url = `https://api.mydomain.com/login/`;
  const { email, password } = props;
  const request = axios.post(url, { email, password });

  return {
    type: LOGIN_USER,
    payload: request
  };
}

export function fetchPages() {
  /* here is where I'd like the header to be attached automatically if the user
     has logged in */ 
  const request = axios.get(PAGES_URL);

  return {
    type: FETCH_PAGES,
    payload: request
  };
}

// reducers.js
const initialState = {
  isAuthenticated: false,
  token: null
};

export default (state = initialState, action) => {
  switch(action.type) {
    case LOGIN_USER:
      // here is where I believe I should be attaching the header to all axios requests.
      return {
        token: action.payload.data.key,
        isAuthenticated: true
      };
    case LOGOUT_USER:
      // i would remove the header from all axios requests here.
      return initialState;
    default:
      return state;
  }
}

我的令牌存储在state.session.token下的redux存储中.

My token is stored in redux store under state.session.token.

我对如何继续感到迷茫.我尝试在根目录中的文件中制作一个 axios实例并进行更新/import而不是从node_modules导入,但在状态更改时不附加标头.非常感谢任何反馈/想法.

I'm a bit lost on how to proceed. I've tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it's not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.

推荐答案

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

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).

希望它会有所帮助:)

这篇关于为所有axios请求附加授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆