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

查看:82
本文介绍了谷歌浏览器中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();
});

但是在 google chrome 的 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 ..

旧:

你必须在你的网址前加上前缀!!

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天全站免登陆