【问题标题】:How to get the request body in morgan() middleware?如何在 morgan() 中间件中获取请求正文?
【发布时间】: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 个中间件有点不舒服(不知道这样行不行)。这就是为什么我在这种情况的潜在解决方案方面遇到了问题:

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

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

【问题讨论】:

    标签: node.js express http morgan


    【解决方案1】:

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

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

    morgan.token('body', req => {
      return JSON.stringify(req.body)
    })
    
    app.use(morgan(':method :url :body'))
    

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

    所以在你使用 morgan 中间件之前你必须放一些 body 解析器:

    app.use(express.json())
    app.use(morgan(':method :url :body'))
    

    注意:express.json 是 Express 中内置的中间件函数。查看更多here

    【讨论】:

      猜你喜欢
      • 2021-01-14
      • 2022-08-09
      • 2021-07-22
      • 2021-10-29
      • 2023-03-13
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2018-04-07
      相关资源
      最近更新 更多