节点快速会话不返回myvar(或不使用相同的sessionID)

时间:2018-03-22 18:54:15

标签: javascript node.js express express-session

在尝试快速会话时,当我将变量存储到会话时,我无法从之前的条目中检索任何内容。不仅如此,我的会话ID已经改变。为什么是这样?

这是我的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');
})

这是前端html:

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

这是我的前端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)
    });
});

以下是命令行(服务器端)的结果:

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

2 个答案:

答案 0 :(得分:1)

fetch API不会自动发送cookie。

使用credentials: "include"发送带有提取GET请求的Cookie。

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.
    })
})

答案 1 :(得分:-1)

尝试不使用cookie maxAge,可能会有帮助。

app.use(session({
  secret: 'xyz',
  resave: false,
  saveUninitialized: true
}));