gpt4 book ai didi

javascript - 如何使用 ExpressJS 和 Nodejs 在控制台中记录 res.locals 内容以进行调试?

转载 作者:行者123 更新时间:2023-11-30 18:05:29 26 4
gpt4 key购买 nike

我正在使用 Node.js 和 ExpressJS 开发一个应用程序,我是这个环境的初学者。我的基本需求是在我的控制台中记录全部或部分 res.locals 的内容以进行调试。

我已经试过了:

var foo_route = function(req, res){

var foo_data = [];

for (var i = 0; i < data.response.foo.length; i++) {

// Here complex data management, not interesting in our case
foo_data = // Bla bla ...

// OK. This displays my object content
console.log(foo_data);

}

// Seems because my misunderstanding of JS scopes, foo_data is still == []
res.locals.data = foo_data;

// Nothing. Both of these two solutions display nothing
console.log(res.locals.data);
console.log(JSON.stringify(res.locals.data, null, 2));

我正在寻找一种 Perl's Data::Dumper , 但似乎我在某处错过了重点,因为它应该是一项非常基本的任务......

编辑:我知道这可能不是一个 ExpressJS 或 Node.js 的问题,而是一个 JS vars 范围的问题......

2018 年阅读本文的人请注意:不要使用 var,请使用 letconst .

最佳答案

尝试使用 eyespect 模块代替 console.log。它以更易于使用的方式打印内容。

npm install -S eyespect

当您在 for 循环中分配 foo_data 时,您是否正在异步执行任何操作?这可能是事情没有按您预期的那样工作的原因

var foo_route = function(req, res){

var foo_data = [];
// what is data here? Also var i should technically be declared at the top of the function
for (var i = 0; i < data.response.foo.length; i++) {

// Here complex data management, not interesting in our case
foo_data = ...

// OK. This displays my object content
console.log(foo_data);

}
// does this print anything interesting?
inspect(foo_data, 'foo data outside the loop')
inspect(res.locals, 'res.locals')
// Seems because my misunderstanding of JS scopes, foo_data is still == []
res.locals.data = foo_data;
inspect(res.locals.data, 'res.locals.data')

// Nothing. Both of these two solutions display nothing
console.log(res.locals.data);
console.log(JSON.stringify(res.locals.data, null, 2));

关于javascript - 如何使用 ExpressJS 和 Nodejs 在控制台中记录 res.locals 内容以进行调试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com