【问题标题】:NodeJS Express — Serve generated index.html public file without saving itNodeJS Express — 提供生成的 index.html 公共文件而不保存它
【发布时间】:2019-03-06 20:44:10
【问题描述】:
使用 express 时,期望您将提供公共目录。
const app = express();
app.use('/', express.static('./public/'));
有没有办法我可以提供一个生成的文件?对于我的应用程序,如果我可以直接构建 index.html,然后直接从内存中提供该“文件”,而不必保存它然后通过“使用”提供它,那将更加方便。
【问题讨论】:
标签:
node.js
express
web-applications
server
code-generation
【解决方案1】:
期望您将提供公共目录
我认为这根本不是期望。许多应用程序只是使用路由而不是创建 REST 微服务。
有两种方法可以做你想做的事。
-
使用带有 NodeJS 的模板引擎和 res.render() 模板。 Check this out 了解更多信息,即使文章使用.pug,您也可以使用these ones。流行的是ejs、车把
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
-
或者您可以在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>');
});