我正在尝试在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);
3 回答
jeck猫
TA贡献1909条经验 获得超7个赞
我用这个:
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);
此代码假定您的控制器位于controllers目录中。此目录中的每个文件应如下所示:
module.exports = function(app){
app.get('/', function(req, res, next){
res.end('hi');
});
}
- 3 回答
- 0 关注
- 1301 浏览
添加回答
举报
0/150
提交
取消