绕开:请求的资源上不存在“Access-Control-Allow-Origin”头 [英] Get around: No 'Access-Control-Allow-Origin' header is present on the requested resource
问题描述
我必须处理一个不受我控制的RESTful服务器。当我尝试从中获取ID 1记录时,这是我得到的错误:
I have to deal with a RESTful server which is not under my control. When I try to fetch the ID 1 record from it this is the error I get:
XMLHttpRequest cannot load http://www.example.com/api/v1/companies/1.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
我可以在shell上 curl
I can curl
it on the shell:
$ curl -I http://www.company.com/api/v1/companies/1
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 11055
Content-Type: application/javascript
Last-Modified: Thu, 18 Jun 2015 07:30:26 GMT
Accept-Ranges: bytes
ETag: "5e772a598a9d01:0"
P3P: policyref="/w3c/p3p.xml",CP="CAO DSP LAW CURa ADMa DEVa CUSi OUR LEG UNI"
Date: Fri, 19 Jun 2015 13:06:46 GMT
$
我使用以下内容SecurityPolicy:
I use the following contentSecurityPolicy:
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self'",
'font-src': "'self'",
'connect-src': "'self' http://www.example.com",
'img-src': "'self'",
'style-src': "'self'",
'media-src': "'self'"
}
我该如何解决?我如何告诉Ember只是使用它?
How can I fix this? How can I tell Ember to just use it?
推荐答案
设置 contentSecurityPolicy
允许浏览器从 http:// localhost:4200
到 http://www.example.com
。
如果您没有此设置,您将看到如下错误:
If you didn't have this set, you would be seeing an error like:
[仅限报告]拒绝连接到 http://www.example.com/ '因为它违反了以下内容安全策略指令:connect-src'self' http:// localhost :* ws:// localhost:* ws:// localhost:35729 ws://0.0.0.0:35729。
[Report Only] Refused to connect to 'http://www.example.com/' because it violates the following Content Security Policy directive: "connect-src 'self' http://localhost:* ws://localhost:* ws://localhost:35729 ws://0.0.0.0:35729".
请求,如果 http://www.example.com
不包含实际允许的特定标题 http:// localhost:4200
来提出这些请求,浏览器会发出错误..
After doing the request, if http://www.example.com
doesn't contain a particular header that actually allows http://localhost:4200
to make these requests, the browser throws an error..
有关更多信息,请查看以下问题: Access-Control-Allow-Origin标头如何工作?
For more information take a look at this question: How does Access-Control-Allow-Origin header work?
如果您使用Ember CLI进行开发,您可以将所有ajax请求代理到 http://www.example.com/
使用:
If you're using Ember CLI for development you can proxy all ajax requests to http://www.example.com/
using:
ember server --proxy http://www.example.com/
但是,移动时这不能解决您的问题到生产。您将需要一些其他解决方案。
But this doesn't solve your problem when moving to production. You will need some other solution for that.
这篇关于绕开:请求的资源上不存在“Access-Control-Allow-Origin”头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!