如何在 node.js 上的 express.js 框架中启用跨域资源共享(CORS)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11181546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:54:43  来源:igfitidea点击:

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

node.jsexpresscorswebservercross-domain

提问by Guy

I'm trying to build a web server in node.js that will support cross-domain scripting, while still providing static files from a public directory. I'm using the express.js and am not really sure how to allow cross-domain scripting (Access-Control-Allow-Origin: *).

我正在尝试在 node.js 中构建一个支持跨域脚本的 web 服务器,同时仍然提供来自公共目录的静态文件。我正在使用 express.js 并且不确定如何允许跨域脚本 ( Access-Control-Allow-Origin: *)。

I saw this post, which I did not find helpful.

我看到了这个帖子,我觉得没有帮助。

var express = require('express')
  , app = express.createServer();

app.get('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

app.configure(function () {
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
});

app.configure('development', function () {

    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {


    var oneYear = 31557600000;
    //    app.use(express.static(__dirname + '/public', { maxAge: oneYear }));
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler());
});

app.listen(8888);
console.log('express running at http://localhost:%d', 8888);

回答by Michelle Tilley

Check out the example from enable-cors.org:

查看enable-cors.org 中的示例

In your ExpressJS app on node.js, do the following with your routes:

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

在 node.js 上的 ExpressJS 应用程序中,对路由执行以下操作:

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

The first call (app.all) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).

第一个调用 ( app.all) 应该在您的应用程序中的所有其他路由(或至少是您希望启用 CORS 的路由)之前进行。

[Edit]

[编辑]

If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static()):

如果您希望标题也显示为静态文件,请尝试此操作(确保它在调用之前use(express.static())

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

I tested this with your code, and got the headers on assets from the publicdirectory:

我用您的代码对此进行了测试,并从public目录中获取了资产的标头:

var express = require('express')
  , app = express.createServer();

app.configure(function () {
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      next();
    });
    app.use(app.router);
});

app.configure('development', function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler());
});

app.listen(8888);
console.log('express running at http://localhost:%d', 8888);

You could, of course, package the function up into a module so you can do something like

当然,您可以将该功能打包到一个模块中,以便您可以执行以下操作

// cors.js

module.exports = function() {
  return function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
  };
}

// server.js

cors = require('./cors');
app.use(cors());

回答by TonyTakeshi

Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

遵循@Michelle Tilley 解决方案,显然它起初对我不起作用。不知道为什么,也许我正在使用 chrome 和不同版本的节点。做了一些小的调整后,它现在对我有用。

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

In case someone facing similar issue as mine, this might be helpful.

如果有人面临与我类似的问题,这可能会有所帮助。

回答by Zahid Rahman

Try to this corsnpm modules.

试试这个corsnpm 模块。

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

该模块提供了许多功能来微调 cors 设置,例如域白名单、为特定 api 启用 cors 等。

回答by Elmer

I use this:

我用这个:

var app = express();

app
.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
})
.options('*', function(req, res, next){
    res.end();
})
;

h.readFiles('controllers').forEach(function(file){
  require('./controllers/' + file)(app);
})
;

app.listen(port);
console.log('server listening on port ' + port);

this code assumes that your controllers are located in the controllers directory. each file in this directory should be something like this:

此代码假定您的控制器位于控制器目录中。这个目录中的每个文件都应该是这样的:

module.exports = function(app){

    app.get('/', function(req, res, next){
        res.end('hi');
    });

}

回答by Jerome Anthony

Recommend using the corsexpress module. This allows you to whitelist domains, allow/restrict domains specifically to routes, etc.,

推荐使用corsexpress 模块。这允许您将域列入白名单,允许/限制域专门用于路由等,

回答by dukegod

You must set Access-Control-Allow-Credentials: true, if you want to use "cookie" via "Credentials"

Access-Control-Allow-Credentials: true如果您想通过“凭据”使用“cookie”,则必须设置

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

回答by Atyos

app.use(function(req, res, next) {
var allowedOrigins = [
  "http://localhost:4200"
];
var origin = req.headers.origin;
console.log(origin)
console.log(allowedOrigins.indexOf(origin) > -1)
// Website you wish to allow to
if (allowedOrigins.indexOf(origin) > -1) {
  res.setHeader("Access-Control-Allow-Origin", origin);
}

// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");

// Request methods you wish to allow
res.setHeader(
  "Access-Control-Allow-Methods",
  "GET, POST, OPTIONS, PUT, PATCH, DELETE"
);

// Request headers you wish to allow
res.setHeader(
  "Access-Control-Allow-Headers",
  "X-Requested-With,content-type,Authorization"
);

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);

// Pass to next layer of middleware
next();

});

});

Add this code in your index.js or server.js file and change the allowed origin array according to your requirement.

将此代码添加到您的 index.js 或 server.js 文件中,并根据您的要求更改允许的原始数组。

回答by user3795430

One additional step I needed to take was to switch my URL from http://localhostto http://127.0.0.0

我需要采取的另一个步骤是将我的 URL 从 切换http://localhosthttp://127.0.0.0