简体   繁体   English

Node JS - CORS - 请求 header 预检响应中的 Access-Control-Allow-Headers 不允许字段授权

[英]Node JS - CORS - Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

I try to upload files to my server and I'm running issues with CORS and Node JS.我尝试将文件上传到我的服务器,但我遇到了 CORS 和 Node JS 的问题。

My server.js file looks like below:我的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');
// pour l'upload
var multer = require('multer');

 const corsOptions = {
   origin: ["http://localhost:3000"],
   credentials: true,
   methods: "POST, PUT, OPTIONS, DELETE, GET",
   allowedHeaders: "X-Requested-With, Content-Type"
 }
 app.use(cors(corsOptions))
 app.options('*', cors(corsOptions));

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

And I have the following issue:我有以下问题:

XMLHttpRequest cannot load http://localhost:4000/users . XMLHttpRequest 无法加载http://localhost:4000/users Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response请求 header 字段 Authorization is not allowed by Access-Control-Allow-Headers in preflight response

and when I try to upload my file, I got a new issue:当我尝试上传我的文件时,我遇到了一个新问题:

POST http://localhost:4000/upload 401 (Unauthorized) POST http://localhost:4000/upload 401(未经授权)

I tried to add many origins in an array instead of only localhost:3000, but nothing changes.我试图在数组中添加许多来源,而不是仅添加 localhost:3000,但没有任何变化。

Anything else: if I add "Origin","Content-Type","Accept" to the list of headers, I have this following error:其他任何东西:如果我将“Origin”,“Content-Type”,“Accept”添加到标题列表,我会出现以下错误:

OPTIONS localhost:4000/users.net::ERR_CONNECTION_REFUSED.选项 localhost:4000/users.net::ERR_CONNECTION_REFUSED。

I got to admit CORS is a bit difficult.我得承认 CORS 有点难。

Thanks谢谢

The code below should work:下面的代码应该工作:

var express = require("express");
var cors = require("cors");
var app = express();

var corsOptions = {
    origin: ' your_url',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }

app.use(function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    // app.header('Access-Control-Allow-Origin', 'http://localhost');
    // app.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    // app.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    // app.header('Access-Control-Allow-Credentials', true);
    next();
});
///products/:id
  app.get('/helloworld', cors(corsOptions), function (req, res, next) {
    res.json({msg: 'This is CORS-enabled for only example.com.'});
  })

  app.listen(3000, function() {
      console.log("CORS-enabled web server listening on port 3000");
  });

var response_text;

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Get the html of the website
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.withCredentials = true;
        xhr.open(method, url, true);
        xhr.send();    
    } else if (typeof XDomainRequest != "undefined") {

      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
      xhr.send();
    } else {

      // Otherwise, CORS is not supported by the browser.
      xhr = null;

    }
    return xhr;
  }

  var url = "your_url";

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    throw new Error('CORS not supported');
  }

  xhr.onload = function() {
    response_text = xhr.responseText;
    console.log(response_text);
    console.log(values);
    // process the response.
   }

   xhr.onerror = function() {
     console.log('There was an error!');
   }

Then cd to the file directory in the terminal and write: $ node filename.js然后cd到终端中的文件目录并写入:$ node filename.js

It will then be listening on http://localhost:3000/helloworld Hope this works.然后它将在http://localhost:3000/helloworld上侦听希望这有效。

To Solve this issue use the below code要解决此问题,请使用以下代码

npm install cors

Add the code in server.js file在 server.js 文件中添加代码

var cors = require('cors')
app.use(cors())

I guess the simplest solution is to add Authorization to Access-Control-Allow-Headers .我想最简单的解决方案是将Authorization添加到Access-Control-Allow-Headers

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

Finally you also want to respond to the preflight OPTIONS request with HTTP ok, eg:最后,您还想用 HTTP ok 响应预检 OPTIONS 请求,例如:

if(req.method === 'OPTIONS') {
    res.status(201);
    res.end();
}
else {
    next();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权 - CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response 请求标头字段在飞行前响应中,Access-Control-Allow-Headers不允许进行授权。 (节点,反应,axios) - Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response. (node, react, axios) 在飞行前响应中,节点Js请求标头字段Access-Control-Allow-Headers不允许Access-Control-Allow-Origin - Node Js Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response 允许使用restify的选项方法 - 请求头字段预检响应中的Access-Control-Allow-Headers不允许授权 - allowing options method with restify - Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response 请求已被 CORS 策略阻止请求 header 字段访问令牌在预检响应节点中被 Access-Control-Allow-Headers 不允许 - Request has been blocked by CORS policy Request header field access-token is not allowed by Access-Control-Allow-Headers in preflight response Node 预检响应中的 Access-Control-Allow-Headers 不允许 Angularjs 请求标头字段 Access-Control-Allow-Headers - Angularjs Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response 预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段身份验证 - Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段内容类型 - Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response NodeJS + ExpressJS:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 - NodeJS + ExpressJS: Request header field not allowed by Access-Control-Allow-Headers in preflight response 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 ack 即使服务器已经允许它 - Request header field ack is not allowed by Access-Control-Allow-Headers in preflight response even the server already allowing it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM