Cors问题只发生在“put”? [英] Cors issue occurs only when "put"?
问题描述
我正在建立一个使用ng资源的Angular应用程式。服务API内置在Asp.Net Core web api中,并且CORS已启用。
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.
service.js代码
The service.js code
.factory('D2Service', ['$resource', function ($resource) {
return $resource('http://localHost:5001/api/D2/:id',
{ id: '@id' },
{
update: { method: 'PUT' }
});
}])
但是,在控制器中调用 D2Service.update(model.d);
时出现以下错误。
However, the call D2Service.update(model.d);
in controller got the following error.
XMLHttpRequest无法加载 http:// localhost: 5001 / api / D2 。对预检请求的响应不通过访问控制检查:在请求的资源上没有Access-Control-Allow-Origin头。原因 http:// localhost:8082 因此不允许访问。
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.
但 D2Service.get({id:model.id})....
运行时没有任何错误。为什么'PUT'有CORS问题,而'GET'很好?
But D2Service.get({ id: model.id })....
runs without any error. Why the 'PUT' has the CORS issue while the 'GET' is fine?
以下是使用fiddler进行监控时的请求/响应。
The following are the request/response when monitoring using fiddler.
请求:
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
回应:
HTTP/1.1 204 No Content
Date: Sun, 27 Nov 2016 23:32:31 GMT
Server: Kestrel
推荐答案
要使预检请求正常工作,您的响应
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
这篇关于Cors问题只发生在“put”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!