最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Fetch with Authorization Header and CORS - Stack Overflow

programmeradmin4浏览0评论

I'm trying to get my request to go through to a online game API that I can't seem to get working. I'm using the Fetch API, and some request require Authorization Bearer token, but the request never gets sent with the authorization header.

I have tried

mode: 'no-cors',
credentials: 'include'

and obviously putting the Authorization in the header like so

header: { 'Authorization': 'Bearer TOKEN' }

but the request still does not go with the authorization. Can anyone point me in the right direction?

EDIT Heres the way I am making the request

fetch(URL, {
  credentials: 'include',
  header: {
    'Authorization': 'Bearer TOKEN'
  }
})

I'm trying to get my request to go through to a online game API that I can't seem to get working. I'm using the Fetch API, and some request require Authorization Bearer token, but the request never gets sent with the authorization header.

I have tried

mode: 'no-cors',
credentials: 'include'

and obviously putting the Authorization in the header like so

header: { 'Authorization': 'Bearer TOKEN' }

but the request still does not go with the authorization. Can anyone point me in the right direction?

EDIT Heres the way I am making the request

fetch(URL, {
  credentials: 'include',
  header: {
    'Authorization': 'Bearer TOKEN'
  }
})
Share Improve this question edited Apr 22, 2018 at 14:52 Steven R asked Apr 22, 2018 at 14:46 Steven RSteven R 3232 gold badges7 silver badges19 bronze badges 4
  • Do you actually have a token for this API? Please show the exact request you are making, and the response that you get. Of course, you should obscure your API key/token... – Matt Morgan Commented Apr 22, 2018 at 14:48
  • I just updated the post @MattMorgan . and I get 2 different responses based whether i use cors or not. If i use mode: 'no-cors' then the authorization never gets sent in the header.... If i use mode: 'cors' (mode is default to 'cors') then the preflight request gets sent and responds with page not available – Steven R Commented Apr 22, 2018 at 14:54
  • Can you provide the actual URL for the API, or is the URL itself private? – Matt Morgan Commented Apr 22, 2018 at 15:03
  • Its not private, but didn't think it was important. its api.guildwars2.com/v2/characters – Steven R Commented Apr 22, 2018 at 15:05
Add a comment  | 

2 Answers 2

Reset to default 15

The key name should be headers, not header.

fetch(URL, {
  credentials: 'include',
  headers: {
    'Authorization': 'Bearer TOKEN'
  }
})

Read the documentation

Keys can be passed either via query parameter or HTTP header. Guildwars API servers do not support preflighted CORS requests, so if your application is running in the user's browser you'll need to use the query parameter.

To pass via query parameter, include "?access_token=" in your request.

发布评论

评论列表(0)

  1. 暂无评论