Angular2 - Cross-Origin Request Blocked

2019-09-13 17:55发布

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 '==='

3条回答
我想做一个坏孩纸
2楼-- · 2019-09-13 18:44

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

查看更多
淡お忘
3楼-- · 2019-09-13 18:56

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)

return this.jsonp
           .get(wikiUrl, { search: params })
           .map(response => <string[]> response.json()[1]);
查看更多
该账号已被封号
4楼-- · 2019-09-13 19:01

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=?'";
return this.jsonp
           .get(body)
           .map(response => <string[]> response.json()[1]);
查看更多
登录 后发表回答