Javascript 使用axios.interceptors拦截请求、管理令牌和令牌续订的正确模式是什么

Javascript 使用axios.interceptors拦截请求、管理令牌和令牌续订的正确模式是什么,javascript,reactjs,react-native,axios,interceptor,Javascript,Reactjs,React Native,Axios,Interceptor,我可能需要一些关于如何使用axios拦截器的帮助。这是登录屏幕的一部分。我想让拦截器在令牌丢失或过期时刷新令牌。我甚至不确定这是一个正确的地方有这个代码作为令牌刷新将需要在登录后也发生。 我有两个axios实例。一个用于API,一个用于auth0。我需要一种方法将它们连接起来,以便它们能够一起工作并可靠 import token from "../../network/axios-auth0"; import client from "../../network/axios-client";

我可能需要一些关于如何使用axios拦截器的帮助。这是登录屏幕的一部分。我想让拦截器在令牌丢失或过期时刷新令牌。我甚至不确定这是一个正确的地方有这个代码作为令牌刷新将需要在登录后也发生。 我有两个axios实例。一个用于API,一个用于auth0。我需要一种方法将它们连接起来,以便它们能够一起工作并可靠

import token from "../../network/axios-auth0";
import client from "../../network/axios-client";  

//Gets token and updates the redux token value
getToken() {
    token.post("token", {
      client_id: config.clientId,
      client_secret: config.clientSecret,
      audience: config.clientAudience,
      grant_type: "client_credentials"
    })
      .then(response => {
        this.props.onUpdateToken(response.data.access_token);
        this.getGroup(response.data.access_token)
      })
      .catch(function (error) {
        console.log(error);
      })
  }

//Gets token from redux and gets data
  getGroup() {
    client.interceptors.request.use(function (config) {
      //call getToken() for new token or check old token
      return config;
    }, function (error) {
      // Do something with request error
      return Promise.reject(error);
    });

    client.get("groups/5ca21cd1cb9134222e397f14", {data: {}, headers: {"Authorization":"Bearer " + this.props.bearerToken}})
      .then(response => {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
  }


  onLoginPress(){
    this.getToken();
  }

  render() {
    return (
      <View>
        <TextInput placeholder={"user"}/>
        <TextInput placeholder={"pass"}/>
        <Button title={"login"} onPress={() => this.onLoginPress()}/>
      </View>
    )
  }

const mapStateToProps = state => {
  return {
    token: state.values.token
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onUpdateToken: (value: string) => dispatch(updateToken(value))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen);

一个人如何专业地做到这一点。我不想为应用程序中的每个调用复制侦听器。

你知道这一点吗?如果我没记错的话,没有,有一个库可以让过程更简单,但我也遇到了一个错误。我可以再试试。你有没有想过这个问题?如果我没记错的话,没有,有一个库应该可以让这个过程更容易,但是我在那里也遇到了一个错误。我可以再试试。
import axios from "axios"
import config from "../config"


const client = axios.create({
  baseURL: config.apiUrl,
  headers: {
    "Content-type": "application/json"
  }
});
client.defaults.headers.get["Content-Type"] = "application/json";

export default client;