用于api调用的Google Chrome中的交叉orgin错误

时间:2016-09-22 05:17:51

标签: angularjs node.js api angular

在nodejs后端我已将此代码添加到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中,谷歌浏览器的客户端正在抛出此错误

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我使用的服务代码

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);

    }

2 个答案:

答案 0 :(得分:1)

<强>更新:

对于新的错误消息:Angular2低于标题。 请更新您的后端以接受content-type

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

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

可以在那里看到你的帖子:http://posttestserver.com/data/

浏览年,月,日和anyNameYouWillFind ..

<强> OLD:

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

this.http.get( '的 HTTP ://本地主机:8080 / v1_user / 45646 /团队');

答案 1 :(得分:0)

通过将其添加到后端node.js

来修复它
// access control --> allowed all origin
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");
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    next();
})

.options('*', function(req, res, next){
    res.end();
})
;