首页 > 解决方案 > 如何在 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 个中间件有点不舒服(不知道这样是否可以)。这就是为什么我面临这种情况的潜在解决方案的问题:

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

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

标签: node.jsexpresshttpmorgan

解决方案


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

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

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 中内置的中间件功能。在这里查看更多。


推荐阅读