[OPTIONS之后未调用POST方法

问题描述 投票:0回答:2

我正在尝试从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"
}
angularjs asp.net-web-api cors same-origin-policy
2个回答
0
投票

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”中缺少令牌“内容类型” *

这是不言自明的。


0
投票

像这样向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>
© www.soinside.com 2019 - 2024. All rights reserved.