我試圖在node.js中構建一個Web服務器,該服務器將支持跨域腳本,同時仍提供靜態文件從一個公共目錄。我正在使用express.js,但我不確定如何允許跨域腳本(Access-Control-Allow-Origin: *
)。如何在node.js上的express.js框架中啓用跨源資源共享(CORS)
我看到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);
注意app.all vs app.get。 這是OPTIONS請求不GET GET –
請參閱[local-web-server](https://github.com/75lb/local-web-server)爲簡單節點的示例,靜態webserver支持CORS – Lloyd
請參閱enable- cors.org/server_apache.html獲取更多信息 – Mostafa