reactjs - 如何在axios内部设置标题
问题描述
我有两个标头,第一个包含 APP_TOKEN,第二个包含 APP_TOKEN 和 USER_TOKEN,如果我的请求在 axios 上只需要 APP_TOKEN 或 APP_TOKEN 和 USER_TOKEN,我该如何设置
这是我的 axios
import axios from 'axios'
export default axios.create((param_app){
if(param_app == APP_TOKEN){
baseURL: 'http://exampe',
headers: {
'timeout' : 30000,
'APP_TOKEN': 'apptoken_example',
}
}else if(param_app === APP_TOKEN && USER_TOKEN){
baseURL: 'http://exampe',
headers: {
'timeout' : 30000,
'APP_TOKEN': 'apptoken_example',
'USER_TOKEN': JSON.parse(localStorage.getItem('data')).TOKEN
}
}
})
例如这个登录页面只需要 APP_TOKEN 作为标题
async handleSubmit(e){
e.preventDefault()
if(this.state.MEMBER_EMAIL && this.state.MEMBER_PASSWORD){
const headers = {
'timeout' : 30000,
'APP_TOKEN': 'example',
}
await API.post('member/login', this.state ,{headers})
.then((response) => {
let responseJson = response
if(responseJson.data.STATUS_CODE === '200'){
this.props.resSave('data', JSON.stringify(responseJson.data.DATA))
this.setState({
redirect: true
})
}else if(responseJson.data.STATUS_CODE === '400') {
alert(responseJson.data.MESSAGE)
this.setState({
redirect: false
})
}
})
}
}
这是需要 APP_TOKEN 和 USER_TOKEN 的页面示例
async componentDidMount() {
const headers = {
'timeout' : 30000,
'APP_TOKEN': 'example',
'USER_TOKEN': JSON.parse(localStorage.getItem('data')).TOKEN
}
await API.get("/banner-home", {headers})
.then(response=>this.setState({
banner:response.data.DATA,
loading:false
}))
}
解决方案
您需要在第一个代码块中切换条件。您首先要检查两个值是否都存在,如果不是,请检查是否只有 APP_TOKEN 存在。目前,如果存在 APP_TOKEN 令牌,则永远不会到达第二次测试。
推荐阅读
- ansible - 使用 privilege_escalation 时,Ansible playbook 执行卡住 - pbrun
- python - 将鼠标悬停在数据点上时显示图表的数据点(x 值、y 值)
- php - 我的代码没有工作并且没有显示任何错误
- python - 如何最小化 Python 中 for 循环生成的多参数函数?
- primefaces - Primefaces 的 ckEditor 无法在服务器端传递完整内容以进行 pdf 下载处理
- postgresql - Patroni,Postgres:无法启动 WAL 流:错误:时间线 X 上请求的起点 Y 不在此服务器的历史记录中
- c# - 使用 OData 端点进行 GET 但性能受到打击,SQL Profiler 显示无法理解的参数
- sql - 如何使用SQL查询今晚和明天早班之间的时间?
- reactjs - Redux Thunk:redux thunk 没有调度一个动作
- android - Android Studio:没有显示完整的生产力指南