[英]How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js
我正在尝试在 node.js 中构建一个支持跨域脚本的 Web 服务器,同时仍然提供来自公共目录的静态文件。 我正在使用 express.js 并且我不确定如何允许跨域脚本( Access-Control-Allow-Origin: *
)。
我看到了这篇文章,但我觉得它没有帮助。
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);
在 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 });
第一次调用 ( app.all
) 应该在你的应用程序中的所有其他路由之前进行 (或者至少是你想要启用 CORS 的路由)。
[编辑]
如果您希望标题也显示为静态文件,请尝试此操作(确保它在调用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();
});
我用您的代码对此进行了测试,并从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);
当然,您可以将函数打包到一个模块中,这样您就可以执行类似
// 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());
按照@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();
});
如果有人遇到与我类似的问题,这可能会有所帮助。
试试这个cors npm 模块。
var cors = require('cors')
var app = express()
app.use(cors())
该模块提供了许多功能来微调 cors 设置,例如域白名单、为特定 api 启用 cors 等。
我用这个:
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);
此代码假定您的控制器位于控制器目录中。 这个目录中的每个文件应该是这样的:
module.exports = function(app){
app.get('/', function(req, res, next){
res.end('hi');
});
}
推荐使用cors express 模块。 这允许您将域列入白名单,允许/限制特定于路由的域等,
如果您想通过“凭据”使用“cookie”,则必须设置Access-Control-Allow-Credentials: true
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();
});
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();
});
将此代码添加到您的 index.js 或 server.js 文件中,并根据您的要求更改允许的原始数组。
我需要采取的额外步骤是将我的 URL 从http://localhost
切换到http://127.0.0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.