curiousJorgeXX
curiousJorgeXX

Reputation: 383

nodejs-express how do I redirect a page to client passing some data from server?

I have this code with session check and i want to pass data from server to client I want to display the session name in the lobby.html page but im new to nodejs express and i dont know how to.

app.get('/lobby', (req, res) => {
    // check session
    sess = req.session;
    if(sess.name) {
        // redirect to lobby.html passing the session name
    }
    else
        res.sendFile(path.resolve(__dirname, './public/client/error.html'));
});
```

Upvotes: 0

Views: 465

Answers (2)

jfriend00
jfriend00

Reputation: 708016

Redirects are by their definition GET requests. The ways to get data from one get request to the next are as follows:

  1. Add a query parameter to the URL you're redirecting to and then have the client or the server parse the data out of the query parameter and adjust the content accordingly.

  2. Set a custom cookie with the data, then do the redirect and have the client or server pull the data from the cookie on the redirected request.

  3. Have the server put some data into the server-side session and have the subsequent redirected request get the data from the session and adjust the content accordingly.

Both #2 and #3 are vulnerable to subtle race conditions if there are multiple incoming requests, the cookie or session data may get acted upon for some other incoming URL rather than the redirected URL unless the data also includes exactly which URL it is supposed to apply to. Option #1 is not susceptible to that type of race condition.

Upvotes: 1

SwishSwish
SwishSwish

Reputation: 158

Looks like req.sess is passed from browser, so why not get name through document.cookie on the browser side directly?

Upvotes: 0

Related Questions