【问题标题】:Cannot display EJS page in node.js web app无法在 node.js Web 应用程序中显示 EJS 页面
【发布时间】:2020-11-29 08:23:31
【问题描述】:

我有一个简单的 nodejs 应用程序,它具有这样的文件夹结构(不是完整的结构,但足以解决这个问题)。

index.js
views
- index.ejs
- about.ejs

index.js,我有

app.use("/", (request, response) => {
  response.render('index')
})
app.use("/about", (request, response) => {
  response.render('about') 
})
// Also tried with extension (index.ejs and about.ejs)

index.ejs,我有

<a href = "../about"> About </a>

问题

  1. 当我转到根 url (localhost:port/) 时,会显示 index.ejs。
  2. 在index.ejs中,我点击链接About,url变成了(localhost:port/about),但是about.ejs没有渲染。但是,在浏览器 (Microsoft Edge Chrominum) 中检查 F12 源时,about.ejs 就在那里。
  3. 当我通过输入 url 到 url 栏直接转到链接时,会显示 index.js。与第 2 步相比,行为(在 F12/sources 中)相同。
  4. 当我注释掉(app.use("/") 块在 index.js 中时,about.ejs 可以访问并显示在屏幕上。
  5. 注意,如果它们是 html 页面并由 node.js 服务器提供,则导航效果很好。一切都只在本地服务器上测试过。

问题 这是什么原因以及如何解决?

为什么要使用 EJS? 我想创建一个基于数据库查询的动态前端。


在 Stackoverflow 上似乎有多个关于此的问题,我已经尝试了多个,但没有一个能解决我的问题,或者清楚地解释原因。

【问题讨论】:

  • use 用于中间件。您应该将get 用于 GET 请求端点。
  • 谢谢,它确实解决了这个问题。虽然我是 Web 开发的新手,但我犯了这个简单的错误很糟糕。

标签: javascript html node.js ejs


【解决方案1】:

正如@Quentin 回答的那样,问题是由于我使用了use。对于请求,在这种情况下是GET,我必须使用get 函数,它解决了问题。 use 适用于我想分解我的 index.js 或使用中间件时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-25
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多