谷歌浏览器中针对API调用的跨域错误 [英] Cross orgin error in google chrome for the api call

查看:530
本文介绍了谷歌浏览器中针对API调用的跨域错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在nodejs后端中,我已将此代码添加到server.js中

in the nodejs backend i have added this code to the server.js

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

但是在谷歌浏览器的angularjs 2客户端中抛出此错误

but in angularjs 2 client side in google chrome is throwing this error

XMLHttpRequest cannot load http://localhost:8080/team. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.

这是我正在使用的angular2的服务代码

this is the service code for angular2 i'm using

export class DataService {
    // URL to web api

    constructor(private http: Http, private _configuration: Configuration,private team:Team) {

        //this.actionUrl = _configuration.ServerWithApiUrl;
        this.actionUrl = "http://localhost:8080/team";

    }
    private actionUrl: string;

    addData(postData: Team): Observable<Team[]> {

        //let body = JSON.stringify({ Team });
        this.team = postData;
        console.log(this.team);
        let body = JSON.stringify({ postData });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        console.log(body);

        return this.http.post(this.actionUrl, body, options)
            .map(this.extractData)
            .catch(this.handleError);

    }

推荐答案

已更新:

对于新的错误消息:Angular2使用较低的标题框. 请也更新您的后端以接受content-type.

For your new error message: Angular2 is lower-casing the headers. Please update your backend to accept content-type too.

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");

您无法测试此URL的帖子: http://posttestserver.com/post.php? dir = anyNameYouWillFind

You cant test post's to this URL: http://posttestserver.com/post.php?dir=anyNameYouWillFind

并且可以在此处查看您的帖子: http://posttestserver.com/data/

And can see your posts there: http://posttestserver.com/data/

浏览到年,月,日和anyNameYouWillFind ..

Browse to year, month, day and anyNameYouWillFind ..

OLD:

您必须在URL前面加上前缀!

you have to prefix your url!!

this.http.get(' http ://localhost:8080/v1_user/45646/team');

this.http.get('http://localhost:8080/v1_user/45646/team');

这篇关于谷歌浏览器中针对API调用的跨域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆