在OPTIONS之后未调用POST方法

时间:2019-11-01 14:49:53

标签: angularjs asp.net-web-api cors same-origin-policy

我正在尝试从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"
}

2 个答案:

答案 0 :(得分:1)

OPTIONS请求设置了以下标头:

Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type

因此它正在询问是否可以执行包含“ content-type”标头的POST请求。

服务器响应:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *

但缺少“ Access-Control-Allow-Headers ”响应标头:

Access-Control-Allow-Headers: content-type

将此添加到OPTIONS响应中,您应该会很好。

可能,控制台中的错误消息是

  

原因:CORS预检频道中CORS标头“ Access-Control-Allow-Headers”中缺少令牌“内容类型” *

这是不言自明的。

答案 1 :(得分:1)

像这样将其他标头添加到您的web.config中...

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>