有一個使用socket.io的服務器。當用戶連接時,它會爲其分配在服務器上創建的用戶標識,然後將其增加1,以便下一個用戶擁有不同的標識。用戶使用套接字連接時創建一個cookie。 io - 節點js
我想爲此使用cookie,以檢查他們是否先前已登錄,如果是,請使用該標識,如果不是,則使用服務器上的標識。
創建一個cookie的方法是使用
res.cookie('cookie', 'monster')
,但我不是在那裏我會穿上它,我試圖把它的連接功能,但水庫難道不存在。如果我把它放在功能之外,我會怎樣稱呼它?這是我的代碼。這是我的服務器的開始:
//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是我希望能夠讀寫餅乾,任何幫助appriciated
您正在引用'res',但它是未定義的。它可能會拋出一個錯誤。 – styfle
這就是我的整個問題 –
你需要傳遞'res'作爲參數。你必須缺少一些代碼,因爲我看不到'initialise()'在任何地方被調用。 – styfle