gpt4 book ai didi

javascript - 当用户与套接字连接时创建 cookie。 io- Node js

转载 作者:行者123 更新时间:2023-12-03 03:42:51 25 4
gpt4 key购买 nike

有一个使用socket.io的服务器。当用户连接时,它会为他们分配在服务器上创建的用户 ID,然后将其加 1,以便下一个用户具有不同的 ID。

我想为此使用 cookie,以检查他们之前是否登录过,如果是,则使用该 ID,如果没有,则使用服务器上的 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 的地方,任何帮助都会得到帮助

最佳答案

我认为您正在寻找的是express采用的中间件模式。您可以根据需要定义任意数量的中间件调用,它们是调用可能需要 res 实例(或 req 实例)的任何其他函数的完美范围。这很重要)。

app.use(function (req, res, next) {
// call function, passing in res here
next();
})

引用:https://expressjs.com/en/guide/using-middleware.html

编辑:

此答案不适合您的情况。在不使用套接字连接的 Node/快速服务器中,那么是的,您可以在范围内需要请求和响应对象的任何地方轻松使用上述模式。

但是,一旦设置了套接字 io 服务器,游戏就会发生变化。在套接字通信期间,范围内不再有明确的请求和响应对象,一切都直接在套接字处理代码和客户端之间处理。所以答案是你需要以套接字 io 方式处理这种情况,而不是以快速方式。

请参阅:Adding a cookie value on Socket.IO

关于javascript - 当用户与套接字连接时创建 cookie。 io- Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com