【发布时间】:2018-01-14 05:25:24
【问题描述】:
有一个使用 socket.io 的服务器。当用户连接时,它将为他们分配在服务器上创建的用户 ID,然后将其增加 1,以便下一个具有不同 ID 的用户。
我想为此使用 cookie,以检查他们是否以前登录过,如果是,则使用该 id,如果没有,则使用服务器上的那个。
创建cookie的方法是使用
res.cookie('cookie', 'monster')
但我没有放在哪里,我试着把它放在连接函数中,但 res 不存在。如果我把它放在函数之外,我该怎么称呼它?这是我的代码。这是我的服务器的开始:
//Require npm modules
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var ejs = require('ejs');
var app = express();
//Set the default user Id to 1 and the default username to Guest
exports.Server = Server = function()
{
this.userId = 1;
this.userName = "Guest";
};
app.set('view engine', 'ejs');
app.get('/game/:id', function (req, res)
{
res.render('game', {game: req.params.id});
});
Server.prototype.initialise = function(port)
{
//Create the server using the express module
this.server = http.createServer(app);
//Declare the 'public' folder and its contents public
app.use(express.static('public'));
//Listen to any incoming connections on the declared port and start using websockets
this.server.listen(port);
this.startSockets();
this.em = new events();
consoleLog('SERVER', 'Running on port: ' + port);
};
Server.prototype.startSockets = function()
{
//When a user connects to the server on the 'game' socket
this.socket = io.listen(this.server);
this.socket.of('game').on('connection', function(user)
{
res.cookie('cookie', 'monster')
//Set their usedId and username
user.userId = this.userId;
user.userName = this.userName + " " + this.userId;
//Increment the user id by 1 so each user with get a unique id
this.userId++;
//Send a response back to the client with the assigned username and user id and initialise them
user.emit('connected', user.userId, user.userName);
this.em.emit('initialiseUser', user.userId, user.userName);
所以我有 res.cookie 的地方就是我希望能够读取和写入 cookie 的地方,任何帮助都会得到帮助
【问题讨论】:
-
您引用了
res,但它未定义。它可能会引发错误。 -
是的,这就是我的全部问题
-
需要传入
res作为参数。您一定缺少一些代码,因为我在任何地方都没有看到initialise()被调用。 -
我从另一个 js 文件初始化它... var server = new Server(); server.initialise(8081);
标签: javascript node.js sockets cookies