9

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.

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
$

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

How can I fix this? How can I tell Ember to just use it?

wintermeyer
  • 8,178
  • 8
  • 39
  • 85

2 Answers2

5

Setting contentSecurityPolicy allows the browser to actually make the request from http://localhost:4200 to http://www.example.com.

If you didn't have this set, you would be seeing an error like:

[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".

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..

For more information take a look at this question: How does Access-Control-Allow-Origin header work?

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.

Community
  • 1
  • 1
jmurphyau
  • 2,309
  • 13
  • 11
1

This may be an old thread, but this answer may help those who refer to this in the future. Try using the @CrossOrigin annotation in the restful method you access. Example:

@CrossOrigin(origins = "http://localhost:4200") 
Meyer
  • 1,662
  • 7
  • 21
  • 20