Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

axios - Set headers based on url

I'm using Axios interceptors to set some data and headers in different requests:

export default ({ $axios }) => {
  $axios.onRequest((req) => {
    if (req.url === 'https://identity.365werk.nl/api/login') {
      console.log('login')
      $axios.defaults.headers['Content-Type'] = 'application/json'
      $axios.defaults.headers.Accept = 'application/json'
    }

    if (req.url === 'https://userservice.365werk.nl/api/v0/auth/social') {
      $axios.defaults.headers['Content-Type'] = 'application/vnd.api+json'
      $axios.defaults.headers.Accept = 'application/vnd.api+json'
    }
  }
}

But the request headers of the response show:

enter image description here

If I add the headers outside the if statement:

export default ({ $axios }) => {
  $axios.defaults.headers['Content-Type'] = 'application/vnd.api+json'
  $axios.defaults.headers.Accept = 'application/vnd.api+json'
  $axios.onRequest((req) => {
    if (req.url === 'https://identity.365werk.nl/api/login') {
      console.log('login')
      $axios.defaults.headers['Content-Type'] = 'application/json'
      $axios.defaults.headers.Accept = 'application/json'
    }

    if (req.url === 'https://userservice.365werk.nl/api/v0/auth/social') {
      console.log('social')
    }
  }
}

enter image description here

But those headers are now also set for the /login url:

enter image description here

Which should just have json headers:

  $axios.defaults.headers['Content-Type'] = 'application/json'
  $axios.defaults.headers.Accept = 'application/json'

Any ideas how to conditionally (based on the url) set the headers of that request?

question from:https://stackoverflow.com/questions/66054292/set-headers-based-on-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...