首页 文章

节点JS - CORS问题对预检请求的响应没有't pass access control check: The value of the ' Access-Control-Allow-Origin'标头

提问于
浏览
1

我正在运行Angular 2网络应用程序的问题 .

在Node JS服务器端,我遇到了CORS预检问题 .

我想在服务器上传文件,当我这样做时,我遇到了这个问题:

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是我的客户端 .

我的 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);
});

最奇怪的是,当我删除以下部分时,上传工作正常:

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

但是,我还有其他问题:

(由于声誉,我在localhost之前没有包含http前缀)

1)zone.js:2019 OPTIONS localhost:4000 / users 404(Not Found)

2)XMLHttpRequest无法加载localhost:4000 / users . 预检的响应具有无效的HTTP状态代码404

3)EXCEPTION:响应状态:URL为0:null

4)未捕获的响应{_body:ProgressEvent,status:0,ok:false,statusText:“”,headers:Headers ...}

我想我们必须在第一个例子中修复cors()部分,但我不知道该怎么做 .

谢谢

更新:使用您的代码修改后,我正在运行一个新问题:

XMLHttpRequest cannot load localhost:4000/users. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

当我尝试上传我的文件时,我遇到了一个新问题:

POST localhost:4000/upload 401 (Unauthorized)

我试图在数组中添加许多来源,而不是只添加localhost:3000,但没有任何变化 .

还有别的:如果我在 Headers 列表中添加“Origin”,“Content-Type”,“Accept”,我有以下错误:

OPTIONS localhost:4000/users net::ERR_CONNECTION_REFUSED.

我承认CORS有点困难 .

1 回答

  • 3

    根据cors docs,https://github.com/expressjs/cors,要启用CORS Pre-Flight,您应该添加以下代码:

    app.options('*', cors()) // include before other 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!'})
    })
    

相关问题