使用快速js 4在节点J中启用CORS

时间:2014-09-13 08:25:40

标签: node.js express

我尝试在启用了CORS的节点服务器中托管独立的JS小部件。 我使用Expressj 4并想要服务器css,js和字体文件。

我现在面临的问题是未加载字体文件

var express = require('express');
var path = require('path');

var methodOverride = require('method-override');
var bodyParser = require('body-parser');


var app = express();


var environmentRoot =  require('path').normalize(__dirname );

app.set('views', environmentRoot + '/public');
app.engine('html', require('ejs').renderFile);

app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(environmentRoot + '/public'));


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


var portNum = process.env.PORT || 3002;

app.listen(portNum, function (a) {
   console.log("Server listening in http://localhost:"+portNum);
});

包JSON

{
   "name": "PackageApp",
   "version": "0.1.0",
   "dependencies": {
      "express" : "~4.9.0",
      "body-parser": "~1.8.1",
      "method-override": "~2.2.0",
      "ejs" : "~1.0.0"
  },
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-html2js": "~0.1.0"
  }
}

1 个答案:

答案 0 :(得分:7)

我会尝试翻译这些陈述:

app.use(express.static(environmentRoot + '/public'));


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

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

app.use(express.static(environmentRoot + '/public'));

我希望在将正文发送到客户端

之前设置标题