浅谈在koa2中实现页面渲染的全局数据
最近用koa2做一个项目的web端,遇到一个场景。
该项目主要用的是传统的服务端渲染的方式,所以会用 koa-views 去做页面的渲染工作。实现方式就是 ctx.render('path',data),那么,有如下场景,每个页面都需要去验证是否登录,登录了要返回页面个人数据,这个情况,怎么办呢?我不想每次都去手动的加入个人数据啊。例如这样:
let data = { "user":"12", "questionList":questionList }; await ctx.render("index",data);
此处的user就是每个页面都是要返回的数据。
很显然,每个页面都要获得的数据,用中间件去获取,类似java的拦截器,过滤器之类的了。
import {UserClient} from "../manager/user/UserClient"; export const signInStatusMiddleware = async (ctx:any,next:any)=>{ console.log("signInStatusMiddleware") let accessToken = ctx.cookies.get("ACCESS-TOKEN"); if(accessToken){ let userClient :UserClient = new UserClient; let user = await userClient.getUserByToken(accessToken); } await next(); }
OK,中间件中已经拿到了用户数据了,那么,问题来了。数据是可以拿,怎么放呢?
找到koa-views 源码。有如下代码:
return function views(ctx, next) { if (ctx.render) return next() ctx.render = function(relPath, locals = {}) { return getPaths(path, relPath, extension).then(paths => { const suffix = paths.ext const state = Object.assign(locals, options, ctx.state || {}) // deep copy partials state.partials = Object.assign({}, options.partials || {}) debug('render `%s` with %j', paths.rel, state) ctx.type = 'text/html' if (isHtml(suffix) && !map) { return send(ctx, paths.rel, { root: path }) } else { const engineName = map && map[suffix] ? map[suffix] : suffix const render = engineSource[engineName] if (!engineName || !render) return Promise.reject( new Error(`Engine not found for the ".${suffix}" file extension`) ) return render(resolve(path, paths.rel), state).then(html => { ctx.body = html }) } }) } return next() }
关键是这一段
const state = Object.assign(locals, options, ctx.state || {})
很显然,state 是将传入的数据,合并了,中间件配置的options ,和ctx.state的。中间件显式配置显然部合适,所以,做法是,在拦截器中间件中,把user赋值给ctx.state.
export const signInStatusMiddleware = async (ctx:any,next:any)=>{ console.log("signInStatusMiddleware") let accessToken = ctx.cookies.get("ACCESS-TOKEN"); if(accessToken){ let userClient :UserClient = new UserClient; let user = await userClient.getUserByToken(accessToken); ctx.state = Object.assign(ctx.state,{"user":user}); } await next(); }
ok。这样一来,在页面渲染的时候,就会带上用户信息了。而不需要再在各处去自己手动添加。
相关推荐
boneix 2020-10-21
MrQuinn 2020-08-16
starzhangkiss 2020-04-19
LorenLiu 2020-03-28
Qimingweikun 2020-03-05
发条戏子 2020-02-01
jackyhungvip 2020-01-19
Qimingweikun 2019-12-09
Anything0 2019-11-17
lert0 2019-11-04
88530198 2019-11-03
sqliang 2019-11-03
苹果咏 2019-07-23
bobbaobao 2018-11-13
lert0 2019-07-01
fanix 2019-07-01
liwenbocsu 2019-07-01