javascript - 使用 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;
专业人士如何做到这一点。我不想为应用程序中的每个调用复制拦截器。
解决方案
推荐阅读
- r - 如何构建一个附加到R中预先存在的数据框的函数
- wordpress - 向 Woocommerce 管理订单页面添加新块
- vmware-clarity - Clarity Design 如何使用例如 .clr-row,只能在内容区域内使用?
- python - JupyterLab - python open() 函数导致 FileNotFoundError
- java - 显示数据并将数据从一个回收视图保存到另一个时出现问题
- java - 访问应用程序时出现 HTTP 500 错误
- sql - postgres 提取 JSON 列键和值以分隔列
- mysql - docker-compose:无法将应用程序容器与 mysql 容器连接
- pdf - 在 next.js 中生成 PDF
- java - 生成逗号分隔值和求和的 Java 代码