javascript - 为什么将 console.log() 放置在呈现视图的函数中时会重复打印一个变量?
问题描述
我有一个简单的全局变量,它在我的app.js
文件中保存一个字符串:
global.MyActivity = "peanutbutterjellytime"
我有另一个文件index.js
是路由器/控制器。在这个文件中,我这样做:
var router = require('express').Router();
console.log(global.MyActivity); // this prints the variable once to the console. Great!
router.get('/', async function (req, res) {
console.log(global.MyActivity); // this prints the variable in duplicate
res.render('index', {pagetitle: 'Activity Page'}); // i think this is causing the problem. if i remove it it works fine
});
module.exports = router;
我总是注释掉方法的console.log(global.MyActivity);
外部,router.get()
所以我知道它不会因为任何附加而重复打印。
我不明白为什么在渲染视图时,控制台会两次打印变量,而如果我删除该渲染代码,它会正确执行并且只打印一次。所以这很好用:
router.get('/', async function (req, res) {
console.log(global.MyActivity); // this prints once
console.log("I am sync"); // this prints once
});
router.get('/', async function (req, res) {
console.log(global.MyActivity); // this prints twice!
console.log("I am async"); // this prints twice!
res.render('index', {pagetitle: 'Activity Page'});
});
如果我想发送global.MyActivity
到我的视图,这会给我带来一个问题,res.render('index', {pagetitle: 'Activity Page', activity: global.MyActivity})
因为它是重复的。我的视图引擎是 express-handlebars,它只是用于 Express 的 Handlebars.js。
更新/修复 1(侥幸,我不明白它为什么起作用) 只是为了踢我放入一个回调函数。这解决了重复控制台日志的问题,但视图永远不会呈现。
router.get('/', async function (req, res) {
console.log(global.MyActivity); // this prints once now! why?
res.render('index', {pagetitle: 'Activity Page'}, function(){ }); // this never renders
});
解决方案
推荐阅读
- visual-studio-2010 - HRESULT 异常:0x800A5023
- python - 使用线程和 Tkinter 库重复任务
- java - 我正在将 instamojo 集成到 android 应用程序中。但我不明白我必须在代码中在哪里设置客户端 ID 和客户端密码
- elementor - 如何使用 CDN 加载 Elementor 资产
- nginx - NodeMediaServer MP4 更改默认视频分辨率 540p
- python-3.x - 有人能告诉我为什么这段代码似乎可以工作,但不能……拜托?
- c++ - 主从动态负载平衡中的无效等级
- java - 写某些单词时如何插入图像?
- kubernetes - 挂载目录的所有权错误
- javascript - 反应前端工作,但对服务器的补丁请求是一个落后的渲染