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

Rez*_*994 3 ajax jquery node.js express angular

我在我的快递申请中有这个代码

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

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

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

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})
Run Code Online (Sandbox Code Playgroud)

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

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 => {});
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

eko*_*eko 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();
});
Run Code Online (Sandbox Code Playgroud)

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

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!')
})
Run Code Online (Sandbox Code Playgroud)