问题描述
我正在学习如何使用中间件,并且有一项任务是使用 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',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
,这应该可以正常工作,但默认情况下不是。您必须使用正文解析中间件来填充它。
所以在你使用摩根中间件之前,你必须放置一些正文解析器:
app.use(express.json())
app.use(morgan(':method :url :body'))
注意:express.json
是 Express 内置的中间件函数。查看更多here。