如何克服从Angular 2到Node/express的CORS? [英] How to overcome CORS from Angular 2 to Node/express?
问题描述
我的快速申请中有此代码
I have this code in my express application
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!')
})
这是我发送请求的Angular 2函数
And this is my angular 2 function that sends the request
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 => {});
}
我在控制台中收到此错误:
I get this error in console:
XMLHttpRequest无法加载 http://localhost:3000/user .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:4200 .
XMLHttpRequest cannot load http://localhost:3000/user. 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:4200' is therefore not allowed access.
但是当我使用jquery ajax发送请求时,它的工作没有任何错误.
But when I send a request using jquery ajax, it's working without any errors.
推荐答案
您可以使用以下代码在nodejs/express中启用CORS:
You can enable CORS in nodejs/express with a code like this:
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();
});
因此您的代码应如下所示:
So your code should look like this:
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!')
})
这篇关于如何克服从Angular 2到Node/express的CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!