This answer references ChatGPT
Middleware can be used in Express to implement the need for uniform handling of code, msg, etc return values. You can write a middleware function that is called on each route response. Here is sample code that implements this middleware:
// 统一返回值中间件
const resultMiddleware = (req, res, next) => {
// 重写 res.json 方法
res.json = (data, code = 0, msg = 'success') => {
res.send({
code: code,
msg: msg,
data: data
})
}
next()
}
// 在 app.js 中引入该中间件
app.use(resultMiddleware)
In this middleware function, we overrode the res.json method to reorganize the incoming parameters into a uniform format for return. In the response of each route, you just need to call the res.json function with the parameters data, code, and msg.
For example, if we wanted to return a piece of data {name: 'Tom', age: 18}, we would write:
app.get('/api/user', (req, res) => {
const data = { name: 'Tom', age: 18 }
res.json(data)
})
The format of the returned data is uniform, as follows:
{
"code": 0,
"msg": "success",
"data": {
"name": "Tom",
"age": 18
}
}
This way you can normalize the format of the interface return values and reduce code redundancy.