You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

渲染EJS文件报错提示posts未定义,无法识别本地JSON属性如何解决?

问题原因
  • 核心原因是渲染user_profile.ejs的控制器没有传递posts参数:你当前贴的postpost是处理POST请求的接口逻辑,仅在提交POST请求到对应路由时才会执行,才会给EJS模板传入posts变量。如果你直接通过GET请求访问个人主页,对应的GET路由控制器没有传递posts参数,就会触发未定义报错。
  • 附带逻辑问题:你当前把postschema.create和postschema.find写为并行异步执行,会出现新创建的帖子还没写入数据库,查询就已经执行完成,返回的帖子列表是旧数据的问题。
修复方案
  1. 给所有渲染user_profile.ejs的路由都补充传参逻辑,比如对应GET访问个人主页的控制器写法如下:
// 对应GET请求访问个人主页的路由控制器
module.exports.getUserProfile = (req, res) => {
  postschema.find({}, (err, doc) => {
    if(err) {
      console.log(err);
      // 出错也传空数组,避免变量未定义
      return res.render("user_profile", { posts: [] });
    }
    return res.render("user_profile", { posts: doc });
  })
}
  1. 优化POST提交接口的异步逻辑,把查询操作放到创建操作的回调中,确保拿到最新数据:
module.exports.postpost = (req,res) => {
  postschema.create({
    content: req.body.content,
    user: req.user._id
  }, (err, newPost) => {
    if(err) console.log(err);
    // 等待创建完成后再查询帖子列表
    postschema.find({}, (err, doc) => {
      if(err) {
        console.log(err);
        return res.render("user_profile", { posts: [] });
      }
      return res.render("user_profile", { posts: doc });
    })
  })
}
  1. 给EJS模板增加容错判断,避免偶发的变量缺失导致页面崩溃:
<h1>Welcome to website</h1>
<%- include('post') %>
<!-- 通过locals判断变量是否存在,locals是EJS内置的参数存储对象 -->
<% if(locals.posts) { %>
  <%= posts %>
  <!-- 后续需要遍历渲染内容可以用下面的写法:
  <% posts.forEach(item => { %>
    <p><%= item.content %></p>
  <% }) %>
  -->
<% } %>

内容的提问来源于stack exchange,提问作者Aman panwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:24:03