I'm getting this error:
XMLHttpRequest cannot load API_URL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
while calling a remote API from localhost. I do not have access to the API server, so I can't allow for CORS on the server side. Here is how I'm calling the API from my Angular service:
this.http.get(url)
.map(response => response.json())
.subscribe(data => this.myData.push(data));
I'd like to use the member myData
afterwards. When looking at chrome's dev tools, I see a 200 message in the networks tab. It also shows the correct JSON Response, but I get the above error in the console and can't use the data.
I've been searching how to fix this. But modifying browser options and server setting is not an option. If possible I want to avoid making a proxy server as well. Also this is the first time I'm using Angular 2, so I don't have a solid understanding of how things work; so it's possible that I should be making requests in a totally different way.
I also tried to add the setting Access-Control-Allow-Origin
to my header as follows:
let headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');
headers.append('Access-Control-Allow-Origin', this.serverName);
this.http.get(url , {headers: headers})
.map(response => response.json())
.subscribe(data => this.myData.push(data));
But that resulted in this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
This time the response was empty. Looking at the request header I don't see Access-Control-Allow-Headers
and Access-Control-Allow-Origin
set the the values of the .append
calls. Am I setting those header options correctly??
Using jsonp instead of http was not helpful either as the application type on the header is set to json:
refused to execute script from API_URL because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
I'd appreciate if you explain a fix in details as I have been unable to follow any solution on the web, perhaps I'm missing some important assumption or must-know.