目前,我正在用express.js和
我想发送这样的通用响应格式:
res.send({status : 'suceess' , msg : '' , data : [] });
来自所有控制器(处理我的路线的功能)
我尝试过的
在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();
}
在middleware.jsstrong文本中
functions responseHandler(req,res)
{
// perform some operation with req.body
res.send(req.body);
}
在server.js中
app.use('/',someFuntion);
app.use(responseHandler);
我只是不想在所有控制器中重复相同的json格式,是
有什么更好的办法吗?
最佳答案
为什么不使用包含res和输入数据的文件来发送。
假设您创建一个文件
responseHandler.js
module.exports = function (res , data){
res.send({status:data.status,msg:data.msg,data:data.data});
};
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();
}
您可以使用这种方法,并且可以更好地对其进行优化。我已经使用了这种方法。您可以在responsehandler文件中使用两个函数,一个用于错误,另一个用于当前数据。