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);
你是什么意思的路线?调用app.listen不够吗? –
不太确定你是如何调用服务器的。从我所知道的是,你通常为你的客户端定义一个端点。例如。 app.get( '钱'/:量)。然后你的REST客户端会执行HTTP GET url = localhost/money/3000。这个端点将是你在服务器上的路由。 –
使用io.on.例如: io.on(“connection”,OnSocketConnection); 然后: 函数OnSocketConnection(pClient) { \t m_pClient = pClient; (“新玩家已连接:”+ pClient.id);我们使用: io.to(pPlayer.nodeID).emit(pEventName,pData);发送数据给特定播放器, –