如何在morgan()中间件中获取请求体?

rd9*_*911 3 http node.js express morgan

我正在学习如何使用中间件,并且有一项任务是使用morgan()中间件发布 JSON 资源。但是当我编写发布某些内容的代码时,我无法获取摩根的主体。

\n
const express = require(\'express\');\nconst morgan = require(\'morgan\');\nconst app = express();\napp.use(morgan(\'tiny\'));\n\nconst generateId = () => {\n    const randNum = Math.floor(Math.random() * 5000)\n    return randNum;\n}\n\nconst isExist = (arr, name) => {\n    const found = arr.find(arrItem => arrItem.name === name) ? true : false\n    return found;\n}\napp.post(\'/api/persons\', (req, res) => {\n    const body = req.body\n    if (!body.name || !body.number) {\n        return res.status(400).json({\n            error: "missing data"\n        })\n    } else if (isExist(notes, body.name) === true) {\n        return res.status(400).json({\n            error: "existed data"\n        })\n    }\n    const note = {\n        id: generateId(),\n        name: body.name,\n        number: body.number\n    }\n    notes = notes.concat(note)\n\n    res.json(note)\n})\nconst PORT = 3001;\napp.listen(PORT, () => {\n    console.log(`Server is worling on ${PORT}`)\n})\n
Run Code Online (Sandbox Code Playgroud)\n

然后我找到了摩根体并使用它,它起作用了。

\n
// ...\nconst morganBody = require(\'morgan-body\')\nconst bodyParser = require(\'body-parser\')\n\napp.use(bodyParser.json())\nmorganBody(app)\n\napp.post(\'/api/persons\', (req, res) => {\n    // the same code as the above\n}\n//...\n
Run Code Online (Sandbox Code Playgroud)\n

但现在,任务是更改控制台中的日志,例如这\n我对在 1 个后端使用 2 个中间件有点不舒服(don\xe2\x80\x99 不知道\xe2\x80\x99 是否可以)。这就是为什么我在这种情况的潜在解决方案方面遇到问题的原因:

\n
    \n
  1. 如何获取morgan()\ 的请求正文(以日志格式和 js 代码格式)以便摆脱morgan-body并写入我的自定义令牌?
  2. \n
  3. 如何编写自定义令牌(找不到任何有关此的文档)以morgan-body摆脱morgan()
  4. \n
\n

因为我是初学者,所以了解哪个选项更可取以及为什么会很有帮助。如果需要任何其他信息或者我的问题有问题,请随时指出。\n提前谢谢您。

\n

Use*_* 28 14

首先,你可以拥有任意数量的中间件,对于大型应用程序,它们往往有很多中间件。

要为摩根创建自定义令牌,您可以执行以下操作:

morgan.token('body', req => {
  return JSON.stringify(req.body)
})

app.use(morgan(':method :url :body'))
Run Code Online (Sandbox Code Playgroud)

req.body如果已设置,这应该可以正常工作,但默认情况下并非如此。您必须使用正文解析中间件来填充它。

因此,在使用摩根中间件之前,您必须放置一些主体解析器:

app.use(express.json())
app.use(morgan(':method :url :body'))
Run Code Online (Sandbox Code Playgroud)

注:express.json是Express中内置的中间件函数。在这里查看更多内容。