我懂速递中间件。它们就像在请求回复之间的隧道。
req -> t1 -> t2 -> t3 -> res
所有中间件都包含三个参数( req, res, next )。next()是将执行传递给下一个隧道的内容。
错误中间件有一点不同,因为它们接受四个参数err, req, res, next。
因此,如果在任何隧道中发生错误,它将跳过其余的通道并将句柄传递给下一个error middleware
我需要用中间件制造一个全球拦截器。
app.js
const express = require('express');
const app = express();
//here I can create a middleware for intercepting the request - which is fine
app.use('*', async function(req, res, next) {
// access req.body here
next();
});
// route handlers
app.get('/', async function(req, res) {
// do stuff
return res.status(200).send({..});
});
// error handler
app.use(async function(err, req, res) {
// log error
return res.status(500).send({...});
});如您所见,我没有将next传递给路由处理程序,而是由一个库将它传递给下一个错误处理程序本身,如果路由处理程序中出现任何错误。
这是我试过的,但出错了。
// route handlers
app.get('/', async function(req, res, next) {
// do stuff
res.status(200).send({..});
next();
});
// error handler
app.use(async function(err, req, res) {
if(!error)
//modify res.body
// log error
return res.status(500).send({...});
});Error ERR_HTTP_HEADERS_SENT:无法在标头发送到客户端后设置它们
我知道,如果我试图再次发送响应,就会发生此错误。
如何访问响应体并在发送之前对其进行修改?
发布于 2022-11-08 14:15:50
创建作为中间件的modifyResponse.js
const mung = require('express-mung');
const encryptdecryptfunctionsv2 = require('../../app/middleware/encryptdecryptv2');
async function redact(body, req, res) {
let response = await encryptdecryptfunctionsv2.responseEncrypt(body);
return { response };
}
module.exports = mung.jsonAsync(redact);然后在server.js中使用
app.use(require('./app/service/modifyResponse.js'));发布于 2020-04-23 13:33:28
我认为,这里唯一的选择不是从处理程序本身发送响应,而是将它传递给另一个中间件。
// route handlers
app.get('/', async function(req, res, next) {
// do stuff
const locals = {
status: 200,
data: data,
message: message,
}
res.locals = locals;
next();
});
// modify locals in another middleware
app.use( async function(req, res) {
// access and modify res.locals
return res.status(res.locals.status).send({
message: res.locals.message,
data: res.locals.data,
});任何人都有更好的选择,请建议。
https://stackoverflow.com/questions/61387942
复制相似问题