Search code examples
angularjsasp.net-web-apicorssame-origin-policy

POST method not being called after OPTIONS


I'm trying to call an API from an angularjs application

var url = "...";
var myObject = {...};
var config = {
    headers : {
        'Content-Type': 'application/json;charset=utf-8;'
    }
};
$http.post(url, myObject, config).then(function(result){...});

Because it's a cross-origin request, it does the preflight, so it calls the OPTIONS method. This is the request header:

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

It returns as 200 OK, with the response header:

{
    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
}

But it doesn't do the POST call afterwards. I tried calling the POST method directly through POSTMAN and it returned just fine. Is there something I'm missing?

EDIT: Heres the console error:

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"
}

Solution

  • The OPTIONS request has these headers set:

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

    so it is asking whether it can do a POST request including the "content-type" header.

    The server responds with:

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

    but it missing "Access-Control-Allow-Headers" response header:

    Access-Control-Allow-Headers: content-type
    

    Add this to the OPTIONS response and you should be good.

    Possible, the error message in the console is

    Reason: missing token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel*

    which is self-explanatory.