使用 fetch 时未发送授权 header
Authorization header not being sent when using fetch
当我尝试将 Authorzation header 设置为如下所示时,header 不会发送到请求的服务器。使用 fetch 设置授权 header 的正确方法是什么?
let options = {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ...'
})
};
fetch('/api/somedata', options).then(function(response) { console.log(response); };
编辑
在网络选项卡的 chrome 开发人员工具中,我收到以下请求:
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
注意没有设置授权 header。
服务器响应:
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
我相信您的服务器需要包含以下响应 header:
Access-Control-Allow-Headers: Authorization
当我尝试将 Authorzation header 设置为如下所示时,header 不会发送到请求的服务器。使用 fetch 设置授权 header 的正确方法是什么?
let options = {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ...'
})
};
fetch('/api/somedata', options).then(function(response) { console.log(response); };
编辑
在网络选项卡的 chrome 开发人员工具中,我收到以下请求:
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
注意没有设置授权 header。
服务器响应:
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
我相信您的服务器需要包含以下响应 header:
Access-Control-Allow-Headers: Authorization