我正在尝试从我的 Koa 2 中间件获取 var 值以显示在我的 pug 模板(或其他)中。例如在 koa-sessions 我有:
app.use(ctx => {
// ignore favicon
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n; // how can I use this?
ctx.body = n + ' views'; // works, but in body directly
ctx.state.views = n + ' views'; // not working
});
另一个例子,响应时间:
app.use(async (ctx, next) => {
const start = Date.now();
ctx.state.start = start
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); // this shows response
ctx.state.ms = await ms>0 // I have no idea what I'm doing :)
});
根据原始指令,这是可行的,但我不想使用正文/控制台,而是将其用作模板变量,因此在我的路由器/控制器中,我将拥有:
...
return ctx.render("posts/index", {
title: 'Posts',
posts: posts,
ms: ctx.state.ms,
views: ctx.session.views // or views: ctx.state.views
});
这些都不起作用。它是否与 async/await 相关,所以它没有及时获得值或者它是一些语法问题?请温柔一点,因为我是新手。:)