首页 > 解决方案 > 如何在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
    }))
  }

标签: reactjsaxiosfetch

解决方案


您需要在第一个代码块中切换条件。您首先要检查两个值是否都存在,如果不是,请检查是否只有 APP_TOKEN 存在。目前,如果存在 APP_TOKEN 令牌,则永远不会到达第二次测试。


推荐阅读