[英]nodejs variable inside express response.write
Assume I have a dynamic way to set the value of toggle
to true
or false
without restarting the app. 假设我有一种动态方法可以在不重新启动应用程序的情况下将
toggle
值设置为true
或false
。
Is there a better way to achieve what I'm trying to do here? 有没有更好的方法来实现我在这里要做的事情? Namely print different results based on the value of
toggle
? 即根据
toggle
值打印不同的结果?
const express = require('express');
const app = express();
const port = 8080;
var toggle = true;
app.get('/', function (req, res) {
res.write(`<!DOCTYPE html>
<html>
<head>
<title>Demo Page</title>
</head>
<body>`);
if (toggle) {
res.write(`<p>Hello World. Toggle Value: true</p>`);
}
else {
res.write(`<p>Hello World. Toggle Value: false</p>`);
}
res.write(`</body></html>`);
res.end();
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
You can concat strings to write single line return 您可以连接字符串以写入单行返回
res.write(`<p>Hello World. Toggle Value: ` + true + `</p>`);
Or using ES6 features 或者使用ES6功能
res.write(`<p>Hello World. Toggle Value: ${true}</p>`);
I would recommend you using some view engine such as mustache or pug, where you would pass 'toggle' variable and handle rendering inside template. 我建议你使用一些视图引擎,如胡子或哈巴狗,你将传递'toggle'变量并处理模板内的渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.