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

创建用户文章新页面时出现Cannot GET /错误求助

问题解决:EJS博客/post/xxx路径无法渲染页面(Cannot GET错误)

核心问题分析

你当前的代码存在两个关键问题:

  1. 使用forEach遍历文章数组时,即使匹配到目标文章并调用res.render,循环仍会继续执行,可能引发重复响应的潜在错误;
  2. 当没有任何文章匹配请求标题时,路由处理函数未发送任何响应,Express会默认返回Cannot GET /post/xxx错误。
    (注:你提到校验时console.log("match found")正常,说明匹配逻辑没问题,但渲染后未正确终止流程或处理边界情况导致失效)

修复方案

方案1:使用find方法(推荐,更简洁高效)

find会在找到第一个匹配项后立即停止遍历,避免无效循环,同时明确处理未找到的场景:

app.get("/posts/:nameOfPost", function(req, res) {
  const requestedTitle = _.lowerCase(req.params.nameOfPost);
  
  // 查找匹配的文章
  const matchedPost = posts.find(post => _.lowerCase(post.titleInput) === requestedTitle);

  if (matchedPost) {
    // 找到则渲染文章页面
    res.render("post", {
      title: matchedPost.title,
      content: matchedPost.content
    });
  } else {
    // 未找到则返回404页面或提示
    res.status(404).render("404", { message: "该文章不存在" });
  }
});

方案2:保留forEach但优化流程

如果坚持使用forEach,需要标记是否找到文章并终止循环,同时处理未匹配场景:

app.get("/posts/:nameOfPost", function(req, res) {
  const requestedTitle = _.lowerCase(req.params.nameOfPost);
  let isPostFound = false;

  posts.forEach(post => {
    if (isPostFound) return; // 已找到则跳过后续循环
    const storedTitle = _.lowerCase(post.titleInput);

    if (storedTitle === requestedTitle) {
      isPostFound = true;
      res.render("post", {
        title: post.title,
        content: post.content
      });
    }
  });

  // 循环结束仍未找到,返回404
  if (!isPostFound) {
    res.status(404).send("抱歉,未找到该文章");
  }
});

额外检查点

  1. 确认post.ejs模板文件存在于views目录下,且模板中正确使用<%= title %>和<%= content %>渲染数据;
  2. 检查post对象的属性名是否正确:你的代码中存储标题用的是post.titleInput,渲染用的是post.title,确保这两个属性都存在且值正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:20:44