node.js - 如何在 morgan() 中间件中获取请求正文?
问题描述
我正在学习如何使用中间件,并且有一项任务是使用morgan()
中间件发布 JSON 资源。但是当我写一个发布东西的代码时,我无法得到摩根的身体。
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('tiny'));
const generateId = () => {
const randNum = Math.floor(Math.random() * 5000)
return randNum;
}
const isExist = (arr, name) => {
const found = arr.find(arrItem => arrItem.name === name) ? true : false
return found;
}
app.post('/api/persons', (req, res) => {
const body = req.body
if (!body.name || !body.number) {
return res.status(400).json({
error: "missing data"
})
} else if (isExist(notes, body.name) === true) {
return res.status(400).json({
error: "existed data"
})
}
const note = {
id: generateId(),
name: body.name,
number: body.number
}
notes = notes.concat(note)
res.json(note)
})
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server is worling on ${PORT}`)
})
然后我找到了 morgan-body 并使用它并且它起作用了。
// ...
const morganBody = require('morgan-body')
const bodyParser = require('body-parser')
app.use(bodyParser.json())
morganBody(app)
app.post('/api/persons', (req, res) => {
// the same code as the above
}
//...
但是现在,任务是更改控制台中的日志,就像 我对在 1 个后端使用 2 个中间件有点不舒服(不知道这样是否可以)。这就是为什么我面临这种情况的潜在解决方案的问题:
- 如何获取
morgan()
请求正文(日志格式和 js 代码格式)以摆脱morgan-body
和编写我的自定义令牌? - 如何编写自定义令牌(找不到任何有关此的文档)
morgan-body
以摆脱morgan()
?
因为我是初学者,所以听到哪个选项更可取以及为什么会有所帮助会很有帮助。如果需要任何其他信息或我的问题有问题,请随时指出。先感谢您。
解决方案
首先,您可以拥有任意数量的中间件,而对于大型应用程序,它们往往拥有大量的中间件。
要为摩根创建自定义令牌,您可以执行以下操作:
morgan.token('body', req => {
return JSON.stringify(req.body)
})
app.use(morgan(':method :url :body'))
如果req.body
已设置,这应该可以正常工作,但默认情况下不是。您必须使用正文解析中间件来填充它。
因此,在使用 morgan 中间件之前,您必须放置一些正文解析器:
app.use(express.json())
app.use(morgan(':method :url :body'))
注意:express.json
是 Express 中内置的中间件功能。在这里查看更多。
推荐阅读
- java - 正则表达式来验证字符串的格式是否正确
- c# - 如何防止字符串在内存中被读取?(C#)
- php - 如何通过 php 中的会话从用户的用户名中获取用户的用户 ID?
- java - Stack Pane:添加 Canvas 和 Imageview 不会导致两者被堆叠
- c# - 范围属性的 MSTest 单元测试
- c++ - 在构造函数中理解`std::move`
- javascript - Javascript 检查网站网址是否可访问
- php - PHP - 如何搜索日期并获得他们的总金额
- android - 如果针对 android over api 21,您是否需要 values-v21/styles.xml?
- html - 摆脱宽度属性并使用其他东西来排列两个文本