解析/格式化api响应(nodejs/express)



我目前正在为从API返回的响应对象的大小/格式而挣扎。

我只是经常发现在我的节点终端中很难看到响应的嵌套对象——跟踪几百行的缩进似乎很难管理,以至于我认为我一定做错了什么?

有什么标准做法或有用的工具我可以使用吗?JSON.stringify((稍微好一点,因为至少我可以看到整个响应,但它只是一堵文本墙,所以问题正好相反。

如果这是显而易见的,请道歉!

您可以从本机节点模块使用util inspect:

// Node.js syntax to demonstrate
// the util.inspect() method
// Importing util library
const util = require('util');
// Object
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;
// Inspect by basic method
console.log("1.>", util.inspect(nestedObject));
// Random class
class geeksForGeeks { }
// Inspecting geeksForGeeks class
console.log("2.>", util.inspect(new geeksForGeeks()));
// Inspect by passing options to method
console.log("3.>", util.inspect(
nestedObject, true, 0, false));
// Inspect by calling option name
console.log("4.>", util.inspect(nestedObject,
showHidden = false, depth = 0, colorize = true));
// Inspect by passing in JSON format
console.log("5.>", util.inspect(nestedObject,
{ showHidden: false, depth: 0, colorize: true }));
// Inspect by directly calling inspect from 'util'
const { inspect } = require('util');
// Directly calling inspect method
// with single property
console.log("6.>", inspect(nestedObject),
{ colorize: true });
// Directly passing the JSON data
console.log("7.>", util.inspect([
{ name: "Amit", city: "Ayodhya" },
{ name: "Satyam", city: "Lucknow" },
{ name: "Sahai", city: "Lucknow" }],
false, 3, true));
// Directly calling inspect method with single property
console.log("8.>", inspect(nestedObject), { depth: 0 });

来源:[https://www.geeksforgeeks.org/node-js-util-inspect-method/]

最新更新