NodeJS Express — 提供生成的 index.html public 文件而不保存

NodeJS Express — Serve generated index.html public file without saving it

使用 express 时,期望您将提供 public 目录。

const app = express();
app.use('/', express.static('./public/'));

有什么方法可以代替 生成的 文件吗?对于我的应用程序,如果我可以直接构建 index.html,然后直接从内存中提供 'file',而不必保存它然后通过 'use' 提供服务,那将会方便得多.

the expectation is that you'll serve a public directory

我认为这根本不是期望。许多应用程序只是使用路由而不是制作 REST 微服务。

您可以通过两种方式做您想做的事。

  1. 使用带有 NodeJS 的模板引擎,并且只是 res.render() 模板。 Check this out for more information, even though the article is using .pug you can use these ones 还有。流行的是ejs, handlebars

    app.get('/', function (req, res) {
        res.render('index', { title: 'Hey', message: 'Hello there!' })
    })
    
  2. 或者你可以把所有东西都写在res.send()里,例如:

    app.get('/', function (req, res) {
        //set the appropriate HTTP header
        res.setHeader('Content-Type', 'text/html');
    
        //send multiple responses to the client
        res.send('<h1>This is the response</h1>');
    });