How do I send data from my route handler to my socket.io function?

William Jones

How do I send data from my route handler to my socket.io function? My code is as follows:

// Game
app.get('/game', (req, res) => {
    const cookies = req.cookies;
    const currentUser = cookies['current_user'];
    const roomName = cookies['room_name'];

    if (roomName) {
        res.render('pages/game', {
            room: roomName
        });
    } else {
        res.redirect('/login');
    }
});

io.of('/game').on('connection', socket => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });

    socket.join(roomName);

    io.of('/game').in(roomName).emit('join', currentUser);
    (async() => {
        const sockets = await io.of('/game').in(roomName).fetchSockets();
        console.log(sockets.length);
    })();
});

I would like the socket to join the room defined in the cookie in the route handler above, but I'm not sure how to get the room name into the socket.io function. I considered putting the socket.io stuff in a function and then passing the data as a parameter, but that would cause the same problem as just putting the socket.io stuff inside the route handler, which as I have learnt from these answers is not the right way to do things. Global variables also don't sound like a good idea - multiple users joining would interfere with each other's data. Any help would be greatly appreciated.

Anvay

You can access the user's cookies by using the socket.handshakes.headers.cookie string. Since this is not an object because it is a header, you need to use the cookie library to convert it into an object.

This is the code that you can use: const cookies = cookie.parse(socket.request.headers.cookie);

Important!

I suggest that you do not use the socket.io-cookie-parser library because has not been updated since 2014 (7 years ago in 2021). However, if you do decide to use it, you must include io.use(cookieParser()); at the top of your code and you can access the cookies from socket.request.cookies or socket.request.signedCookies if using a secret. Please go to the documentation for more information.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I send a message to my socket.io websocket from the command line in linux?

How do I detect that my attempt to send data via TLS secured socket has failed?

I am trying to send an array of loader function to my route it throws an error Handler is not a funtion in a reactJs application

How can I send data (string) from my html to my server (node or express) and execute certain function with it?

how do i use the data my click handler sends me

How do I call my function from within my function?

Can't send fetched data to my socket.io stream?

How do I properly route data through my Node API?

How do I setup my API route to delete data from Material table?

How do i make my music bot send embed from a function when song is played?

(Socket.SendTo) How do I response/send back data to the client that my server began receive? C#

How do I serialize my result from my .each function?

How do I use the input from my box to my function?

How do I send a data from Validator::extend() to Validator::replacer() so that my message can be more detailed?

How do I pass arguments to my handler

How do I get my data from my DB as a variable?

How do I get my Data to return from my IpcMain

How do I send email from my domain?

how do I send my date from datepickerfragment to another fragment

How can I change my route into a function?

How do I discover my socket type?

how can i split an instance of my packet class into chunks and send them with socket_sendto function?

socket.io | Should I wrap my route handlers inside io.on('connection')?

How do I get my node/socket.io app to use the correct port when deployed to heroku?

How do I make my Node.js websocket socket.io server more resilient to DoS?

How do I send my "abline" gridlines to appear behind my barplot data?

How do I handle errors in a function called from a route handler in Express, NodeJS?

How do I route my domain name to my server?

How do I pass an input variable from Data Factory to my durable function

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive