3
votes

I'm building an Angular app which use ng-resource. The service API is built in Asp.Net Core web api and the CORS is already enabled.

The service.js code

.factory('D2Service', ['$resource', function ($resource) {
    return $resource('http://localHost:5001/api/D2/:id',
        { id: '@id' },
        {
            update: { method: 'PUT' }
        });
}])

However, the call D2Service.update(model.d); in controller got the following error.

XMLHttpRequest cannot load http://localhost:5001/api/D2. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.

But D2Service.get({ id: model.id }).... runs without any error. Why the 'PUT' has the CORS issue while the 'GET' is fine?

The following are the request/response when monitoring using fiddler.

Request:

OPTIONS http://localhost:5001/api/D2 HTTP/1.1
Host: localhost:5001
Connection: keep-alive
Access-Control-Request-Method: PUT
Origin: http://localhost:8082
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:8082/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8

Response:

HTTP/1.1 204 No Content
Date: Sun, 27 Nov 2016 23:32:31 GMT
Server: Kestrel
1
to properly support CORS, your server needs to respond to preflight requests (OPTIONS) - that is how CORS works - Jaromanda X
How to make the server respond to preflight requests? I'm using Asp.net core on dotnet core. - ca9163d9
that's what google is for - to search how to do these things - docs.microsoft.com/en-us/aspnet/core/security/cors - Jaromanda X
I've added services.AddCors(); and app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader())` but it still not working. - ca9163d9
I see no "options.addPolicy" as per the documentation section about preflight - Jaromanda X

1 Answers

0
votes

For preflight request to work you should have following header in your response:

Access-Control-Allow-Origin: YOUR_DOMAIN
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: YOUR_CUSTOM_HEADERS