NodeJS Express - 提供生成的index.html公共文件而不保存它

问题描述 投票:0回答:1

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

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

有没有办法可以代替生成的文件?对于我的应用程序,如果我可以直接构建index.html,然后直接从内存中提供“文件”,而不必保存它只是通过'use'来提供它,那将会更方便。

node.js express web-applications server code-generation
1个回答
1
投票

期望您将服务于公共目录

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

有两种方法可以做你想做的事。

  1. 使用带有NodeJS的模板引擎,只需使用res.render()模板。 Check this out获取更多信息,即使该文章使用.pug,您也可以使用these ones。流行的是ejs,车把 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>'); });
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.