Authorization header not being sent when using fetch

允我心安 提交于 2020-04-30 07:49:59

问题


When I try and set the Authorzation header as below the header doesn't get sent to the server for the request. What's the correct way to set the Authorization header with fetch?

let options = { 
  method: 'GET', 
  headers: new Headers({ 
    Authorization: 'Bearer ...' 
  }) 
};
fetch('/api/somedata', options).then(function(response) { console.log(response); };

Edit

In chrome developer tools on the network tab I get this for the request:

GET /api/somedata HTTP/1.1
Host: someserver.azurewebsites.net
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Accept: */*
Referer: http://localhost:3000/somedata
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

Note there's no Authorization header being set.

And the server responds:

HTTP/1.1 401 Unauthorized
Content-Length: 61
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
WWW-Authenticate: Bearer
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Date: Thu, 29 Sep 2016 03:16:15 GMT

回答1:


I believe your server needs to include the following response header:

Access-Control-Allow-Headers: Authorization


来源:https://stackoverflow.com/questions/39760659/authorization-header-not-being-sent-when-using-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!