我在RealWorld实例之后编写了一个Sapper应用程序,其中包含会话管理
polka()
.use(bodyParser.json())
.use(session({
name: 'kidways-app',
secret: 'conduit',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 31536000
},
store: new FileStore({
path: 'data/sessions',
})
}))
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
pdfMiddleware,
sapper.middleware({
session: req => ({
token: req.session && req.session.token
})
})
)
.listen(PORT, err => {
if (err) console.log('error', err);
});然后在我的_layout.sevlte上
<script context="module">
export async function preload({ query }, session) {
console.log('preload', session)
return {
// ...
};
}
</script>
<script>
import { onMount, createEventDispatcher } from 'svelte';
import { Splash } from 'project-components';
import * as sapper from '@sapper/app';
import { user } from '../stores';
import client from '../feathers';
const { session } = sapper.stores();
onMount(async () => {
try {
await client.reAuthenticate();
const auth = await client.get('authentication');
user.set(auth.user);
$session.token = 'test';
} catch (e) {
} finally {
loaded = true;
}
});
console.log($session)
</script>
<h1>{$session.token}</h1>这个工作在客户端呈现,但令牌仍然是未定义的预加载,使我的SSR模板呈现中断。
我错过了什么?
发布于 2020-02-23 18:34:17
当页面呈现时,根据您在这里指定的函数的返回值填充session:
sapper.middleware({
session: req => ({
token: req.session && req.session.token
})
})因此,虽然客户端可能有最新的令牌,但除非您以会话中间件知道的方式将令牌持久化到服务器,否则它不会在页面重新加载时生效。
通常情况下,您可以通过一个服务器路由来实现这一点,比如routes/auth/token.js之类的.
export function post(req, res) {
req.session.token = req.body.token;
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end();
}...and从客户端发布令牌:
onMount(async () => {
try {
await client.reAuthenticate();
const auth = await client.get('authentication');
user.set(auth.user);
await fetch(`auth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ token })
});
// writing to the session store on the client means
// it's immediately available to the rest of the app,
// without needing to reload the page
$session.token = 'test';
} catch (e) {
} finally {
loaded = true;
}
});https://stackoverflow.com/questions/60355894
复制相似问题