淺談在koa2中實(shí)現(xiàn)頁(yè)面渲染的全局?jǐn)?shù)據(jù)
最近用koa2做一個(gè)項(xiàng)目的web端,遇到一個(gè)場(chǎng)景。
該項(xiàng)目主要用的是傳統(tǒng)的服務(wù)端渲染的方式,所以會(huì)用 koa-views 去做頁(yè)面的渲染工作。實(shí)現(xiàn)方式就是 ctx.render('path',data),那么,有如下場(chǎng)景,每個(gè)頁(yè)面都需要去驗(yàn)證是否登錄,登錄了要返回頁(yè)面?zhèn)€人數(shù)據(jù),這個(gè)情況,怎么辦呢?我不想每次都去手動(dòng)的加入個(gè)人數(shù)據(jù)啊。例如這樣:
let data = {
"user":"12",
"questionList":questionList
};
await ctx.render("index",data);
此處的user就是每個(gè)頁(yè)面都是要返回的數(shù)據(jù)。
很顯然,每個(gè)頁(yè)面都要獲得的數(shù)據(jù),用中間件去獲取,類似java的攔截器,過(guò)濾器之類的了。
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,中間件中已經(jīng)拿到了用戶數(shù)據(jù)了,那么,問題來(lái)了。數(shù)據(jù)是可以拿,怎么放呢?
找到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()
}
關(guān)鍵是這一段
const state = Object.assign(locals, options, ctx.state || {})
很顯然,state 是將傳入的數(shù)據(jù),合并了,中間件配置的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。這樣一來(lái),在頁(yè)面渲染的時(shí)候,就會(huì)帶上用戶信息了。而不需要再在各處去自己手動(dòng)添加。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
優(yōu)化Node.js Web應(yīng)用運(yùn)行速度的10個(gè)技巧
這篇文章主要介紹了優(yōu)化Node.js Web應(yīng)用運(yùn)行速度的10個(gè)技巧,本文講解了從并行、異步、緩存、gzip 壓縮、客戶端渲染等等技巧,需要的朋友可以參考下2014-09-09
node thread.sleep實(shí)現(xiàn)示例
這篇文章主要介紹了node thread.sleep實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
利用node+koa+axios實(shí)現(xiàn)圖片上傳和回顯功能
這篇文章為大家詳細(xì)介紹了如何利用node+koa+axios實(shí)現(xiàn)圖片上傳和回顯功能,主要實(shí)現(xiàn)簡(jiǎn)單的圖片上傳和靜態(tài)內(nèi)容的訪問,感興趣的可以了解一下2022-05-05
Node中的util.promisify()方法的基本使用和實(shí)現(xiàn)
眾所周知,在JS中實(shí)現(xiàn)異步編程主要是通過(guò)以下幾種方案,回調(diào)函數(shù),觀察者模式,Generator,Promise,async / await ,今天就和大家一起聊一下在node中的一個(gè)util.promisify()這個(gè)API的基本使用和基本實(shí)現(xiàn)2023-07-07
從零開始學(xué)習(xí)Node.js系列教程五:服務(wù)器監(jiān)聽方法示例
這篇文章主要介紹了Node.js服務(wù)器監(jiān)聽方法,結(jié)合實(shí)例形式分析了nodejs事件監(jiān)聽相關(guān)操作技巧,需要的朋友可以參考下2017-04-04

