Search code examples
javascriptnode.jsexpressexpress-session

Node express-session not returning myvar(or not using the same sessionID)


When trying out express-session, I couldn't retrieve anything from my previous entries when I stored a variable to a session. Not only that, my session ID has changed. Why is this?

Here is my server.js:

const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')

const app = express()

app.use(express.static(__dirname + "/src"))
app.use(bodyParser.json())
app.use(session({secret: 'tester', saveUninitialized: true, resave: false, cookie: {maxAge: 5*60000}}))


app.get("/",(request, response) => {
    response.sendFile(__dirname + "/front_end.html")
    //response.end('This is a test for stuff')
})

app.post("/resources", (request, response)=>{
    request.session.myvar = "Hello Person"
    console.log(request.session.myvar);
    console.log(request.sessionID)
    response.json({message: "Success", url: "/respond"})
})

app.get("/respond", (request, response)=>{
    console.log(request.session.myvar)
    console.log(request.sessionID)
    response.send('stuff')
})

app.listen(3000, (err) => {
    if (err) {
        console.log('Server is down');
        return false;
    }
    console.log('Server is up');
})

Here is the front end html:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <button id="test">Test</button>
        <script src="/front_end.js"></script>
    </body>
</html>

And this is my front end js:

document.getElementById("test").addEventListener("click", () => {
    fetch('/resources', {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "name": "Test",
            "pass": "Tester"  //ignore the fact that this actually doesn't do anything yet.
        })
    }).then((response) => {
    return response.json()
    }).then((json)=>{
        window.location.assign(json.url)
    });
});

Here is the result from the command line(server end):

Server is up
Hello Person
DQH0s5Mqu9FasN5It49xD1ZAtkCbj0P5
undefined
p5_imn5FXxxO-i2lR62TNGXEd-o2WHGP

Solution

  • fetch API does not send cookies automatically.

    use credentials: "include" to send the cookies with the fetch GET request.

    https://developers.google.com/web/updates/2015/03/introduction-to-fetch

    fetch('/resources', {
        method: "POST",
        credentials: "include",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "name": "Test",
            "pass": "Tester"  //ignore the fact that this actually doesn't do anything yet.
        })
    })