节点JS-CORS对预检请求的响应未通过访问控制检查:"Access-Control-Allow-Origin"标头的值 [英] Node JS - CORS Issue Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header
问题描述
我的Angular 2网络应用程序出现问题.
I'm running an issue with my Angular 2 web app.
在Node JS服务器端,我遇到了CORS预检问题.
On Node JS server side, I got an issue with CORS preflighting.
我想在服务器上上传文件,当我这样做时,我会遇到这个问题:
I want to upload a file on the server, and when I do it, I have this issue :
XMLHttpRequest无法加载 http://localhost:4000/up .对预检请求的响应未通过访问控制检查:当请求的凭据模式为包括"时,响应中"Access-Control-Allow-Origin"标头的值不得为通配符"*".因此,不允许访问来源' http://localhost:3000 . XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制.
XMLHttpRequest cannot load http://localhost:4000/upload. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
其中localhost:4000是我的服务器,而localhost:3000是我的客户端.
where localhost:4000 is my server and localhost:3000 is my client.
我的 server.js 文件是这样的:
require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
var multer = require('multer');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// // use JWT auth to secure the api
app.use(expressJwt({ secret: config.secret }).unless({ path: ['/users/authenticate', '/users/register'] }));
// // routes
app.use('/users', require('./controllers/users.controller'));
app.use('/challenges', require('./controllers/challenges.controller'));
// NEW UPLOAD
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
/** Serving from the same express Server
No cors required */
app.use(express.static('../client'));
app.use(bodyParser.json());
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
console.log(req.file);
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
// FIN NEW UPLOAD
// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
console.log('Server listening on port ' + port);
});
最奇怪的是,当我删除以下部分时,上传正常:
The weirdest thing is that, when I remove the following part, the upload is working :
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// // use JWT auth to secure the api
app.use(expressJwt({ secret: config.secret }).unless({ path: ['/users/authenticate', '/users/register'] }));
// // routes
app.use('/users', require('./controllers/users.controller'));
app.use('/challenges', require('./controllers/challenges.controller'));
但随后,我又遇到了其他问题:
But then, I got other issues :
(由于信誉,我没有在本地主机之前添加http前缀)
(I did not include http prefix before localhost due to reputation)
1)zone.js:2019选项localhost:4000/用户404(未找到)
1) zone.js:2019 OPTIONS localhost:4000/users 404 (Not Found)
2)XMLHttpRequest无法加载localhost:4000/users.飞行前的响应具有无效的HTTP状态代码404
2) XMLHttpRequest cannot load localhost:4000/users. Response for preflight has invalid HTTP status code 404
3)例外:状态为0的URL响应:空
3) EXCEPTION: Response with status: 0 for URL: null
4)未捕获的响应{_body:ProgressEvent,状态:0,确定:false,statusText:",标头:Headers…}
4) Uncaught Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}
我认为我们必须在第一个示例中修复cors()部分,但我不知道该怎么做.
I think we have to fix the cors() part in the first example but I don't know what to really do.
谢谢
更新:用您的代码修改后,我正在运行一个新问题:
UPDATE : After modifying with your code, I'm running a new issue :
XMLHttpRequest无法加载localhost:4000/users.请求标头字段在飞行前响应中,Access-Control-Allow-Headers不允许授权
当我尝试上传文件时,出现了一个新问题:
and when I try to upload my file, I got a new issue :
POST本地主机:4000/上传401(未经授权)
我试图在数组中添加许多起源,而不仅仅是localhost:3000,但没有任何变化.
I tried to add many origins in an array instead of only localhost:3000, but nothing changes.
其他任何事情:如果将"Origin","Content-Type","Accept"添加到标题列表中,则会出现以下错误:
Anything else : if I add "Origin","Content-Type","Accept" to the list of headers, I have this following error :
OPTIONS localhost:4000/users net :: ERR_CONNECTION_REFUSED.
我不得不承认CORS有点困难.
I got to admit CORS is a bit difficult.
推荐答案
根据cors文档, https://github.com/expressjs/cors ,要启用CORS飞行前检查,您应该添加以下代码:
According to the cors docs, https://github.com/expressjs/cors, to enable CORS Pre-Flight you should add the following code:
app.options('*', cors()) // include before other routes
您还可以为特定的路线启用它:
You can also enable it for specific routes:
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
这篇关于节点JS-CORS对预检请求的响应未通过访问控制检查:"Access-Control-Allow-Origin"标头的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!