【发布时间】:2020-02-27 20:52:07
【问题描述】:
我正在尝试从 angularjs 应用程序调用 API
var url = "...";
var myObject = {...};
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
};
$http.post(url, myObject, config).then(function(result){...});
因为是跨域请求,所以会进行预检,所以会调用 OPTIONS 方法。 这是请求头:
Host: ...
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: pt-BR
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:9000/....
Origin: http://localhost:9000
DNT: 1
Connection: keep-alive
它返回 200 OK,并带有响应头:
{
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Fri, 01 Nov 2019 14:31:29 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: Microsoft-IIS/10.0
Vary: X-Requested-With
X-Frame-Options: GOFORIT
X-Powered-By: Nette Framework, ASP.NET
}
但之后它不会进行 POST 调用。我尝试通过 POSTMAN 直接调用 POST 方法,它返回得很好。我有什么遗漏吗?
编辑:这是控制台错误:
Possibly unhandled rejection:
{
"data":null,
"status":-1,
"config":{
"method":"POST",
"transformRequest":[null],
"transformResponse":[null],
"jsonpCallbackParam":"callback",
"headers":{
"Content-Type":"application/json;charset=utf-8;",
"Accept":"application/json, text/plain, */*"
},
"url":"...",
"data":{...},
"cached":false
},
"statusText":"",
"xhrStatus":"error"
}
【问题讨论】:
-
尝试不同的浏览器,以避免预检缓存问题,还在 ASP.NET 中将超时缓存预检设置为 0,尽管在 .NET Core 或经典中执行此操作的方式会有所不同。
-
我在 firefox 和 chrome 上都试过了,但仍然没有调用 POST
-
-1的状态表示请求被浏览器阻止。开发者控制台将有一条错误消息指出原因。 Postman 可以工作,因为它不强制执行same-origin policy。
标签: angularjs asp.net-web-api cors same-origin-policy