Javascript 当Curl命令成功时,fetch选项返回http401
这就是我的获取代码的样子Javascript 当Curl命令成功时,fetch选项返回http401,javascript,rest,curl,fetch-api,Javascript,Rest,Curl,Fetch Api,这就是我的获取代码的样子 let getSummary = (year, month) => { let url = baseUrl + "/rest/monthlySummaries/" + localStorage.getItem("paUserId") + "/" + year + "/" + month; let authHeaders = { "Content-Type": "application
let getSummary = (year, month) => {
let url = baseUrl + "/rest/monthlySummaries/" +
localStorage.getItem("paUserId") + "/" + year + "/" + month;
let authHeaders = {
"Content-Type": "application/json",
"Accept": "application/json",
"Bearer": localStorage.getItem("paToken")
};
console.log("summary url:", url, ",headers:", authHeaders);
return fetch(url, {
method: "GET",
headers: authHeaders
});
};
由于这是GET
请求,浏览器使用HTTP选项进行preflight
请求,以确保它们确实进行httpget
请求。我记下打什么电话,我明白了
summary url: https://api.myapp.com/rest/monthlySummaries/userId/2017/4 ,headers: Object {Content-Type: "application/json", Accept: "application/json", Bearer: "41afa8432aaa411e48b6c1c637c77cb3:userId:84000000"}Accept: "application/json"Bearer: "41afa8432aaa411e48b6c1c637c77cb3:userId:84000000"Content-Type: "application/json"__proto__: Object
2VM50885:1 OPTIONS https://api.myapp.com/rest/monthlySummaries/cca6b151-cab4-4de2-81db-9a739a62ae88/2017/4 401 (Unauthorized)
然而,当我在curl
上做类似的事情时,一切都正常
curl -v -X OPTIONS -H"BEARER:e3310afc4dcd68d80d56a83bddfd4a09:userId:564000000" "https://api.myapp.com/rest/monthlySummaries/userId/2017/4"
* Trying 52.23.254.96...
* Connected to api.myapp.com (52.23.254.96) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
* Server certificate: DigiCert SHA2 High Assurance Server CA
* Server certificate: DigiCert High Assurance EV Root CA
> OPTIONS /rest/monthlySummaries/userId/2017/4 HTTP/1.1
> Host: api.myapp.com
> User-Agent: curl/7.43.0
> Accept: */*
> BEARER:e3310afc4dcd68d80d56a83bddfd4a09:userId:564000000
>
< HTTP/1.1 200 OK
< Date: Mon, 29 May 2017 23:21:11 GMT
< Server: WildFly/8
< X-Powered-By: Undertow/1
< Access-Control-Allow-Headers: origin, content-type, accept, authorization
< Allow: HEAD, GET, OPTIONS
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Credentials: true
< Content-Type: text/plain
< Content-Length: 18
< Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD
< Access-Control-Max-Age: 1209600
< Vary: Accept-Encoding
<
* Connection #0 to host api.myapp.com left intact
在响应中也可以看到这一点请参见您配置的位置
.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
您不允许使用承载
头,也不是传递消息的正确方式
你可能是说
"Authorization": `Bearer ${localStorage.getItem("paToken")}`
发送Bearer
时,如果它不在允许的标题列表中,则会导致飞行前验证失败。这是CORS请求,因此您需要提供OPTIONS
方法,是服务器端的nodejs应用程序吗?如果是,那么只需安装CORS包()并使用(require('CORS')())代码>是的,服务器有点不舒服,但正如您在CURL
response上看到的响应,具有正确的标题,并验证为well@daydreamersimple curl不会执行飞行前请求以获取cors允许的方法,但浏览器获取代码可以。同样:需要从状态为200 OK的服务器中选择服务器选项方法。完全同意(:
"Authorization": `Bearer ${localStorage.getItem("paToken")}`