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

新手上路,请多包涵

我有一个从 api 服务器获取令牌的 react/redux 应用程序。在用户进行身份验证后,我想让所有 axios 请求都将该令牌作为 Authorization 标头,而不必手动将其附加到操作中的每个请求。我对 react/redux 还很陌生,不确定最好的方法,也没有在谷歌上找到任何高质量的点击。

这是我的 redux 设置:

 // 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 存储中。

我对如何进行有点迷茫。我已经尝试在我的根目录中的文件中创建一个 axios 实例 并更新/导入它而不是从 node_modules 但是当状态更改时它没有附加标题。非常感谢任何反馈/想法,谢谢。

原文由 awwester 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 749
2 个回答

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

1.可以使用 axios拦截器 拦截任何请求,添加授权头。

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

    return config;
});

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

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

所以在你的情况下:

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

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

 (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'];
         */
     }
})();

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

希望能帮助到你 :)

原文由 Hardik Modha 发布,翻译遵循 CC BY-SA 4.0 许可协议

创建 axios 实例:

 // Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

然后对于任何请求,将从 localStorage 中选择令牌并将其添加到请求标头中。

我使用此代码在整个应用程序中使用相同的实例:

 import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

原文由 llioor 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进