Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...