Express.js 无法获取 index.ejs 文件

Express.js can't get index.ejs file

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

我尝试制作在访问 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.mjsreturnsCannot 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?

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

在这种情况下关键是这一行

// 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>

输出: