【问题标题】:Express.js can't get index.ejs fileExpress.js 无法获取 index.ejs 文件
【发布时间】:2022-01-28 18:57:16
【问题描述】:

对不起,这是基本问题,但我不能自己解决这个问题。

我尝试制作快速服务器,在访问http://localhost:3000 时响应index.ejs 文件。我想做的很简单。我的服务器代码如下。

server.mjs

import express from 'express';
import path from 'path';

const app = express();

console.log(process.cwd());
console.log(path.join(path.resolve(), 'views'));

app.set('views', path.join(path.resolve(), '/views'));
app.set('view engine', 'ejs');
app.get('/', (res, req) => {
    res.render('index');
});

app.listen(3000, () => {
    console.log(`Example app listening on port 3000`);
});

以上server.mjs返回Cannot GET /index.ejs页面,浏览器控制台显示GET http://localhost:3000/index.ejs 404 (Not Found)消息。

项目目录树如下。

.
├── node_modules
├── package-lock.json
├── package.json
├── server.mjs
└── views
    └── index.ejs

上面代码中process.cwd和path.join的结果如下。

//the result of process.cwd()
/Users/****/Documents/IntelliJ project/****

//the result of path.join()
/Users/****/Documents/IntelliJ project/****/views

index.ejs的路径配置错了吗?为什么服务器没有得到index.ejs

我的项目环境在这里。
操作系统:MacOS v11.6
IDE:IntelliJ IDEA 2021.2
node.js:v14.17.0
express.js:v4.17.2
ejs:v3.1.6

【问题讨论】:

  • path.join(path.resolve(), 'views')); 应该是path.join(__dirname, 'views'));, RTM
  • 注释掉app.set('views', path.join(path.resolve(), '/views'));,然后重试。由于您的视图位于“视图引擎”的默认位置,因此无需再次设置。
  • 它工作正常!交换参数(req, res)是很容易犯的错误,但我没有意识到。谢谢!

标签: node.js express ejs


【解决方案1】:

在这种情况下,关键是这条线

// set the view engine to ejs
app.set('view engine', 'ejs');

在您的代码中,您不必要地重复 app.set 两次:

app.set('views', path.join(path.resolve(), '/views'));

之后,你误用了这个函数,你交换了参数(req,res) 这会导致错误TypeError: res.render is not a function:

// app.get("/", (req, res) ! properly !
app.get("/", (res, req) => {
  res.render("index");
});

我注释掉了您代码中的多余行。其余解决方案如下。

pacakge.json

{
  "name": "express",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.2"
  }
}

项目文件和文件夹结构

server.js

import express from "express";
// import path from "path";
const port = 3000;
const app = express();

app.set("view engine", "ejs");

// console.log(process.cwd());
// console.log(path.join(path.resolve(), "views"));

// app.set("views", path.join(path.resolve(), "/views"));

app.get("/", (req, res) => {
  res.render("index");
});

app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});

index.ejs

<!DOCTYPE html>
<html lang="en">
  <head></head>
  <body>
    <h1>It works fine!</h1>
  </body>
</html>

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多