简体   繁体   English

用于res.send的Express.js中间件,在每个res.send()上调用函数

[英]Express.js middleware for res.send , call function on each res.send()

Currently I am making api's with express.js and 目前,我正在用express.js和

I want to send common response format like this : 我想发送这样的通用响应格式:

res.send({status : 'suceess' , msg : '' , data : [] });

From all the controllers (functions handling my routes) 来自所有控制器(处理我的路线的功能)


What I have tried : 我尝试过的

in someController.js someController.js中

someFuntion(req,res,next)
{
    // these two lines will be in each controller , that I don't want
    // want it to be automated , and minimal as much as possible
    res.body({status : 'suceess' , msg : '' , data : [] });
    next();
}

in middleware.js strong text 在middleware.js 强文本中

functions responseHandler(req,res)
{
    // perform some operation with req.body
    res.send(req.body);
}

in server.js server.js中

app.use('/',someFuntion);
app.use(responseHandler);

I just don't want to repeat same json format in all the controllers , is there any better way to do it ? 我只是不想在所有控制器中重复相同的json格式,还有更好的方法吗?

Why not you use a file which take res and the input data to send . 为什么不使用包含res和输入数据的文件来发送。 Suppose you create a file 假设您创建一个文件

responseHandler.js responseHandler.js

module.exports = function (res , data){

   res.send({status:data.status,msg:data.msg,data:data.data});
};

controller.js controller.js

var response = require("responseHandler");

someFuntion(req,res,next)
{
    // these two lines will be in each controller , that I don't want
    // want it to be automated , and minimal as much as possible
   // res.body({status : 'suceess' , msg : '' , data : [] });
    data.status = 'sucess';
    data.msg='';
    data.data=[];
    response(res,data)
    next();
}

You can use this approach and can better optimize it . 您可以使用这种方法,并且可以更好地对其进行优化。 I have used this approach. 我已经使用了这种方法。 You can use two function in responsehandler file one for error and one for current data. 您可以在responsehandler文件中使用两个函数,一个用于错误,另一个用于当前数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM