【发布时间】:2020-04-07 04:49:14
【问题描述】:
我正在使用 express-session 尝试使用会话,但它似乎没有找到或保存会话。
我希望每次调用后响应都会增加,但是随着 Postman 或基本的苗条应用程序的重复请求,它会一直返回 0。
如何让它找到已经保存的会话并返回递增的值?
Node.js:
const express = require('express')
const app = express()
const session = require('express-session');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:5000"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(session({
genid: function(req) {
return 1
},
proxy: true,
secret: "max",
resave: false,
saveUninitialized: true
}));
app.get('/', function (req, res) {
console.log(req.session)
if (!req.session.views) {
req.session.views=0;
}
res.send((req.session.views++).toString());
console.log(req.session)
})
app.listen(3000)
基本苗条:
<script>
export let name;
let resp = "";
async function sendReq() {
resp = await fetch("http://localhost:3000/");
console.log(resp);
resp = await resp.text();
console.log(resp);
}
</script>
<main>
<h1>Hello {name}!</h1>
<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
<button on:click={sendReq}>Click me</button>
{resp}
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
【问题讨论】:
-
修改会话对象后,应该做
session.save()。另外,您为什么要硬编码genId()以每次都返回相同的ID?除非您出于某些特定原因自己生成会话 ID,否则请删除此方法并让默认行为为您工作。
标签: node.js express session express-session