灏天阁

Node/Koa2[52]: 加载更多

· Yin灏

个人主页 API 路由

src/routes/api/blog-profile.js

const router = require("koa-router")();
const { loginCheck } = require("../../middlewares/loginChecks");

const { getProfileBlogList } = require("../../controller/blog-profile");

const { getBlogListStr } = require("../../utils/blog");

router.prefix("/api/profile");
// 加载更多
router.get("/loadMore/:userName/:pageIndex", loginCheck, async () => {
  const { userName, pageIndex } = ctx.params;
  pageIndex = parseInt(pageIndex);
  const result = await getProfileBlogList(userName, pageIndex);
  // 渲染模板字符串
  result.data.blogListTpl = getBlogListStr(result.data.blogList);
  ctx.body = result;
});

处理 ejs 模板

  • 安装 ejs 依赖
npm i ejs --save
  • 处理具体逻辑

src/utils/blog.js

const ejs = require("ejs");
const fs = require("fs");
const path = require("path");

const BLOG_LIST_TPL = fs
  .readFileSync(path.join(__dirname, "..", "views", "widgets", "blog-list.ejs"))
  .toString();

function getBlogListStr(blogList = [], canReply = false) {
  return ejs.render(BLOG_LIST_TPL, {
    blogList,
    canReply,
  });
}

module.exports = {
  getBlogListStr,
};

app.js 中注册路由

//...
const profileAPIRouter = require("./routes/api/blog-profile");
//...
app.use(profileAPIRouter.routes(), profileAPIRouter.allowedMethods());

- Book Lists -