2016-06-22 64 views
1

我有一个NodeJS应用程序,我用作游戏服务器。NodeJS Express应用程序不调用app.use

我想用它来设置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); 

回答

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,对于混淆道歉。假设它是一个简单的服务器,在某个端口上侦听,所以对于这种情况,根本不需要表示。有一些研究和解决方案出来了;

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

+0

你是什么意思的路线?调用app.listen不够吗? –

+1

不太确定你是如何调用服务器的。从我所知道的是,你通常为你的客户端定义一个端点。例如。 app.get( '钱'/:量)。然后你的REST客户端会执行HTTP GET url = localhost/money/3000。这个端点将是你在服务器上的路由。 –

+1

使用io.on.例如: io.on(“connection”,OnSocketConnection); 然后: 函数OnSocketConnection(pClient) { \t m_pClient = pClient; (“新玩家已连接:”+ pClient.id);我们使用: io.to(pPlayer.nodeID).emit(pEventName,pData);发送数据给特定播放器, –

相关问题