只能 http 模块将 ejs 渲染到 html 并将 pug 渲染到 html?

Can only http module render ejs to html and pug to html?

如果是 http 模块,它有编码 utf8 的选项,但我认为 express 模块没有选项,是这样吗?现在有通过 express 渲染的方法吗?

const express = require('express');
const ejs = require('ejs');
const fs = require('fs');

const app = express();

app.use('/','utf8',(request,response) =>{
    fs.readFile('./render.ejs',(err,data)=>{
       fs.send(data) 
    });
});

app.listen(2000, ()=>{
    console.log('http://127.0.0.1:2000');
})

这段代码只是为了报错

概览

Pug、ejs - 这些是模板引擎的示例,您的问题的答案是:是的,express 支持它。更重要的是你甚至可以创建自己的模板引擎并在应用程序中使用它可以带来很多乐趣(来自官方文档的教程:Developing template engines)。

要使用例如pug,您必须安装它:

  • npm install pug --saveyarn add pug

告诉 express 你要使用那个特定的:

  • app.set('view engine', 'pug')

示例

假设您已经安装了 pug、express 并且您的应用程序中有该模板:

html
  head
    title= title
  body
    h1= message

因此,要使用自定义标题和消息来呈现它,请这样做:

app.get('/hello-world', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

当有人使用 GET 请求请求 '/hello-world' 路径时,它将提供 html 模板:

  • <title></title> 在头元素容器中 -> Hey
  • <h1></h1> 在 body 元素中 -> Hello there!.

完整示例如下:Doc example