我有一个NodeJS应用程序我用作游戏服务器。
我正在尝试用它设置CORS,但app.use似乎没有被调用。
任何人都知道为什么?
var util = require("util"); // Utility resources (logging, object inspection, etc)
var fs = require('fs');
var express = require("express");
var app = express();
var port = 3000;
app.use(function (req, res, next) {
// these never get printed out:
util.log( "app.use adding Access-Control-Allow-Origin" );
console.log( "app.use adding Access-Control-Allow-Origin" );
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://example.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
var server = app.listen(port, function(){
console.log('CORS-enabled web server listening on port ' + port);
});
var io = require('socket.io').listen(server);
答案 0 :(得分:1)
查看npm cors
包。 https://www.npmjs.com/package/cors
所有请求都将启用CORS的示例用法:
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get('/my_API_URL/:id', function(req, res, next){
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
在他们的页面上,他们还有其他例子,其中CORS仅在单一路线上启用。
另外,只是想知道你是如何测试你的应用程序的?您还没有在示例代码中定义任何路由。
正如评论部分所指出的那样,@ Nitzan Wilnai没有做REST API,为这种混乱道歉。它假设是一个侦听某个端口的简单服务器,因此在这种情况下,您可能根本不需要 express 。是否有一些研究和解决方案出来了;
io.configure('development', function(){
io.set('origins', '*:*');
}
OR
io.set( 'origins', '*domain.com*:*' );
参考文献: Socket.io doesn't set CORS header(s)
以防您尝试构建聊天程序。这是一个示例项目; https://github.com/socketio/socket.io