Skip to content Skip to sidebar Skip to footer

Angular2 - Cross-origin Request Blocked

I'm trying to use the forecast API with my angular2 app. However, when i try to access the API I get a Cross-Origin Error. Any idea how i can fix this error ? search(latitude: any

Solution 1:

For forecast.io, you should use JSONP. The easiest way to do this using jQuery is adding ?callback=? to request URL:

$.getJSON('https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + "?callback=?", function(data) {
   console.log(data);
});

I am no expert on Angular 2 but reading the docs it looks like you need to import the Jsonp and then add a callback. More documentation here -- see the section app/wiki/wikipedia.service.ts.

I think something like the code below will work for you

let body = "https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + '?callback=?'";
returnthis.jsonp
           .get(body)
           .map(response => <string[]> response.json()[1]);

Solution 2:

Check out the cors bits on angular.io

https://angular.io/docs/ts/latest/guide/server-communication.html#!#cors

Something like the below (from above)

returnthis.jsonp
           .get(wikiUrl, { search: params })
           .map(response => <string[]> response.json()[1]);

Solution 3:

You are getting this problem because the header you are sending does not match the headers in the backend.

Suppose you send the following headers:

contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Your token used in app'); 
contentHeaders.append('Content-Type', 'application/json'); 
contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like Authorization, Content-type, and Access-Control-Allow-Origin should match the allowed headers in your backend.

So in the backend Access-Control-Allow-Headers should have all above headers:

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, content-type, Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to pass all headers which you send from frontend: 'Authorization', 'Content-type', and 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Hope this post will helpful for you

Thanks

Post a Comment for "Angular2 - Cross-origin Request Blocked"