最近用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。這樣一來,在頁面渲染的時候,就會帶上用戶信息了。而不需要再在各處去自己手動添加。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答