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

我看到了this post个,但我觉得没有帮助.

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

推荐答案

查看the example from enable-cors.org:

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

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的路由)之前进行.

[编辑]

如果您希望静态文件的标题也显示出来,请try 以下操作(确保在调用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目录中获取了assets资源 的标题:

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

Node.js相关问答推荐

如何使用updateMany()和Node.js的方法?

仅当所需文档是最后一个文档时才更新MongoDB,否则插入

JsonwebToken过期后如何注销和清除cookie?

如何在医学中按patientId查找一个并同时插入多个数据

为什么 mongoose 没有常规数组方法

我的 MERN 网站一直告诉我我的一个函数不是一个函数

Rails 7导入npm yaml包时出现404错误

try 使用 pdf.js 时 pdf.getPage 不是函数

运行本地移动自动化测试时,在onPrepare钩子中,ERROR @wdio/cli:utils: A service failed in the 'onPrepare'

Node.js中使用ffmpeg如何获取视频截图的位置?

mongoose 7.0.3 使用运算符 $and 严格搜索日期

Nodejs 从链接数组中获取数据并保存到 mongodb

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

错误:找不到模块'C:\Users\nguye\AppData\Local\nodejs\node_modules\npm\bin\npm-cli.js'

NodeJS为exec设置环境变量

Base64 编码一个 javascript 对象

node/express:使用 Forever 连续运行脚本时设置 NODE_ENV

React Native ios build:找不到 node

PhoneGap/Cordova Android 开发

在 Node.js 中获取终端的宽度