这个代码有什么问题? 我正在尝试从使用 Express 的 NodeJS 应用程序中显示请求对象。
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
console.log(JSON.stringify(req));
});
app.listen(3000);
我收到以下错误。
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle
at JSON.stringify (<anonymous>)
at /Users/user/Desktop/test/app.js:8:19
at Layer.handle [as handle_request] (/Users/user/Desktop/test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/user/Desktop/test/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/user/Desktop/test/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/user/Desktop/test/node_modules/express/lib/router/layer.js:95:5)
at /Users/user/Desktop/test/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/user/Desktop/test/node_modules/express/lib/router/index.js:335:12)
at next (/Users/user/Desktop/test/node_modules/express/lib/router/index.js:275:10)
at jsonParser (/Users/user/Desktop/test/node_modules/body-parser/lib/types/json.js:110:7)
删除JSON.stringify()
,它将记录。
对于人类可读的输出,您需要util.inspect
; 它也具有提高可读性的不错选项:
console.log(
util.inspect(req, {
depth: 5,
colors: true,
}),
);
JSON 不接受循环对象 - 引用的对象 他们自己。JSON.stringify(( 如果遇到错误,将抛出错误 其中之一。
只需尝试console.log(req);
,您将获得正确的预期输出。