查看来自enable-cors.org的示例:
在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.jsmodule.exports = function() { return function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); };}// server.jscors = require('./cors');app.use(cors());


