【发布时间】:2021-08-02 09:20:43
【问题描述】:
我正在学习如何使用中间件,并且有一项任务是使用 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()?
因为我是初学者,所以了解哪个选项更可取以及为什么会这样会很有帮助。如果需要任何其他信息或我的问题有问题,请随时指出。 提前谢谢你。
【问题讨论】:
标签: node.js express http morgan