我已经用Node.js和Koa / Express写了一个网站。
我的app.js中有这条路线:
router.use('/about/', about.routes()
router.use('/blog/', blog.routes()
router.use('/imprint/', imprint.routes())
router.use('/', index.routes())
router.use('/user/:id/', user.routes())
app.use(router.routes())
此路线的每个页面都有相同的全局侧边栏,其中包含有关最新博客的信息。现在我在每条路线上都有一个查询(边栏上的博客)。
query database for blogs -> save result to variable -> render page with sidebar
是否可以在每个请求中查询一次并将结果设置为全局变量并将其共享到路由?
例:
1: User visit the website
2: Koa query the results for the the sidebar (route: /)
3. User see the sidebar on the webpage
4: User click on a blog (new page route: /blog/)
5: Koa share the result of the sidebar (Point 2)
6: User see the sidebar on the webpage
...
通常使用中间件,然后使用附加数据自定义装饰koa上下文(或请求)来执行此操作:
app.user ((ctx, next) => {
query_database_for_blogs.then(res =>{
ctx.req.sidebar = res
return next()
})
})