发送每个请求唯一的axios标头实例吗?

时间:2018-11-08 18:46:37

标签: javascript axios

在将实例创建为param之后(不是默认值),是否可以发送axios标头?

假设我通过.create()有一个基本实例

export const api = axios.create({
  baseURL: BACKEND_URL,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

我想发送经常更新的JWT令牌。存在到同一实例的401错误(要求更新令牌)的路由。当我进行令牌刷新时,仍会通过另一个401将Authorization标头附加到send和backend上,从而导致无限循环。

StackOverflow上的大多数答案都会导致axiosIntance.defaults.header更新,但是该解决方案对我不起作用

// I don't want defaults, just specific for this particular request
// api.defaults.headers['Authorization'] = 'JWT ' + this.props.onboardingToken

// can i send header in params instead ? It doesnt work with this syntax taken from officials docs
const params = {
  headers: {
    'Authorization': 'JWT ' + this.props.onboardingToken
  },
  data: {
    name: name
  }
}


api
  .patch(`company/${companyId}`, params)
  .then(res)
  .catch(err => {
    if (err.response.status === 401){
      this.refreshToken();
    }
  })

因此,此错误处理请求也附带了标头

 refreshToken = () => {
    const token = this.props.urlToken

    onboardingApi
      .post('login-token', {"token": token})
      .then(res => {
        this.repeatPatch()
      })
      .catch(err => {
      })
  }

0 个答案:

没有答案
相关问题