首页 > 解决方案 > 使用 axios.interceptors 拦截请求和管理令牌和令牌更新的正确模式是什么

问题描述

我可能需要一些帮助如何在这里使用 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);

我的意思是每次 axios 调用都需要拦截器(以防止请求因旧令牌而卡住)所以最好将它附加到实例。但是后来我不知道如何从定义实例的文件中更新 redux 中的令牌。这可能也不是最佳做法。这是定义的 2 个实例之一。

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;

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

标签: javascriptreactjsreact-nativeaxiosinterceptor

解决方案


推荐阅读