我想将Morgan中间件返回的请求和请求正文解析为Winston流函数。
我尝试使用JSON.parse()
但它给出了错误uncaughtException: Unexpected token o in JSON at position 1
morgan.token('reqBody', function (req: any, res: any) {
return JSON.stringify(req.body)
});
我的温斯顿配置代码:
module.exports.stream = {
write: function (message: any, encoding: string) {
console.log('req:', message);
}
输出:
{"remote_addr":"::1", "id":"2ebb876e-6d42-4087-bc80-f2a617dd6bc3",
"remote_user":"-","date":"26/Aug/2019:15:29:00+0000","method":"POST","url":"/department/2/employees","http_version":"1.1","status":"400","result_length":"16","referrer":"-","user_agent":"PostmanRuntime/7.15.2","response_time":"206.975","request_body":"{"name":"John Chris","Type":"C"}","response_body":"-"}
当我打印JSON
上面在Winston配置中显示的请求时,我无法解析它。您可能已经注意到 req 对象,request_body 是一个子对象,并以"{ "name: "John Chris".....}"
. 我不确定带大括号的额外引号是否会导致问题,但我无法找到解析它的方法。如果摩根返回req.body
而不是JSON.stringify(req.body)
然后我得到[Object object]
我再次未能解析。