我正在使用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>
我正在使用express-session尝试使用该会话,但似乎找不到或保存该会话。我希望每次调用后响应都会增加,但是如果使用...
fetch()
默认情况下不随其请求发送cookie。因此,如果没有Cookie,则您的服务器不会看到会话Cookie,因此不会找到您之前的会话对象。您需要添加credentials: "include"
或credentials: "same-origin"
选项: