如何克服从Angular 2到Node / express的CORS?

时间:2017-04-14 08:15:43

标签: jquery node.js ajax angular express

我在快递申请中有这段代码

getData() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    let params = 'username=test';

    this.http.post('http://localhost:3000/user', params, {headers: headers})
        .map(res => res.json())
        .subscribe(data => {});
}

这是我发送请求的角度2函数

{{1}}

我在控制台中收到此错误:

  

XMLHttpRequest无法加载http://localhost:3000/user。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:4200”访问。

但是当我使用jquery ajax发送请求时,它的工作没有任何错误。

1 个答案:

答案 0 :(得分:7)

您可以使用以下代码启用nodejs / express中的CORS:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

所以你的代码应该是这样的:

var app = require('express')()
var bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*'); //<-- you can change this with a specific url like http://localhost:4200
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

app.post('/user', function (req, res) {
    res.send(req.body.username);
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})