Javascript 分析来自expressjs morgan winston中间件的json请求时出错

Javascript 分析来自expressjs morgan winston中间件的json请求时出错,javascript,json,express,winston,morgan,Javascript,Json,Express,Winston,Morgan,我想将Morgan中间件返回的请求和请求正文解析为Winston流函数 我试图使用JSON.parse(),但它给出了错误uncaughtException:JSON中位置1处的意外标记o morgan.token('reqBody', function (req: any, res: any) { return JSON.stringify(req.body) }); 我的Winston配置代码: module.exports.stream = { write: function

我想将Morgan中间件返回的请求和请求正文解析为Winston流函数

我试图使用
JSON.parse()
,但它给出了错误
uncaughtException:JSON中位置1处的意外标记o

 morgan.token('reqBody', function (req: any, res: any) {
  return JSON.stringify(req.body)
 });
我的Winston配置代码:

 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
时,它显示在上面的Winstonconfig中,我无法解析它。正如您可能已经注意到的req对象一样,request_body是一个子对象,以
“{”name:“John Chris”…}”
开头。我不确定带大括号的额外引号是否会导致问题,但我无法找到解析它的方法。如果morgan只返回
req.body
而不是
JSON.stringify(req.body)
然后我得到
[对象]
我再次解析失败。

我不知道Winston/Morgan是什么。但我强烈怀疑你应该删除
JSON。stringify
位置1处JSON中意外的标记o是你尝试
JSON时得到的。解析
已经解析过的东西。它需要一个字符串,所以它强制它为字符串是
[object object]
[
是有效的-它可以是JSON数组。但是
o
不是-没有有效的JSON字符串以
[o
开头。这就是为什么它在位置1(基于0)说它是
o
但是我不明白你最后一句话的后半部分,除非你在
控制台中用
+
替换了
。log
。我不知道Winston/Morgan是什么。但我强烈怀疑你应该删除
JSON。当你不这样做时,JSON中位置1处的
意外标记o就是stringify
ry to
JSON.parse
已解析的内容。它需要一个字符串,因此它将其强制为
[object object]
字符串。
[
是有效的-它可以是JSON数组。但是
o
不是-没有有效的JSON字符串以
开头[o
。这就是为什么它在位置1(基于0)上说它是一个
o
。但是我不理解你最后一句话的后半部分,除非你在
控制台中将
替换为
+
。log