首页 > 解决方案 > 解析/格式化 api 响应(nodejs/express)

问题描述

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

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

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

如果这很明显,请道歉!

标签: node.jsexpressresponse

解决方案


您可以从本机节点模块使用 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/]


推荐阅读