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, longitude: any){
console.log(latitude);
console.log(longitude);
let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude ;
console.log(body);
this.http.get(body)
.map(
response => response.json()
).subscribe(
data => console.log("Data: "+data),
err => console.log("Error: "+err),
() => console.log('Get Complete')
);
}
Error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.forecast.io/forecast/APIKEY/37.8267,-122.423. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Update Now using JSONP
let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude + '?callback=?' ;
console.log(body);
this.jsonp.get(body)
.map(response => response.json())
.subscribe(
data => console.log("Data: "+data),
err => console.log("Error: "+err),
() => console.log('Get Complete')
);
Error
Error0.def29191127bbc3e0100.hot-update.js:59:10 Object { _body: "JSONP injected script did not invok…", status: 200, ok: true, statusText: "Ok", headers: Object, type: 3, url: "https://api.forecast.io/forecast/60…" }0.def29191127bbc3e0100.hot-update.js:61:10 SyntaxError: expected expression, got '==='
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:
So those headers like
Authorization
,Content-type
, andAccess-Control-Allow-Origin
should match the allowed headers in your backend.So in the backend
Access-Control-Allow-Headers
should have all above headers: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
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)
For forecast.io, you should use JSONP. The easiest way to do this using jQuery is adding
?callback=?
to request URL: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