简体   繁体   English

React Axios 实例:How to get Token from redux store to put it on my axios instance

[英]React Axios instance : How to get Token from redux store to put it on my axios instance

I want to create an instance of Axios to use for my HTTP calls, the problem is the token stored on my redux, I don't know how to get it and put it in my configuration, because UseSelector is a part of the functional component but in my case, I have a javascript configuration like this:我想创建一个 Axios 实例以用于我的 HTTP 调用,问题是存储在我的UseSelector上的令牌,我不知道如何获取它并放入我的组件配置中,因为它是功能的一部分但就我而言,我有这样的 javascript 配置:

import axios from 'axios';

const axiosClient = axios.create();

axiosClient.defaults.baseURL = 'https://example.com/api/v1';

axiosClient.defaults.headers = {
  'Content-Type': 'application/json',
  Accept: 'application/json'
};

//All request will wait 2 seconds before timeout
axiosClient.defaults.timeout = 2000;

axiosClient.defaults.withCredentials = true;

Does anyone of you know how to get the Token variable from redux in this case, please?请问有谁知道在这种情况下如何从 redux 获取 Token 变量? thank you!谢谢你!

There are multiple ways to do it, and I like the Axios interceptor approach.有多种方法可以做到,我喜欢 Axios 拦截器方法。

const instance = axios.create({
  baseURL: "base_url",
}); 

instance.interceptors.request.use(function (config) {
  const token = store.getState()?.user?.userData?.token;
    config.headers.Authorization = token;
    return config;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM