Proper Way To Return Json Format Using Node Or Express
My question is actually copied from Proper way to return JSON using node or Express. I need the response in this format. Sample format for response API { 'success':true, 'code':2
Solution 1:
If you are using express, don't send the message from the controller. Make a middleware that's main purpose is to send the response to the client. This will give you a power of setting the format of consist response to the client.
For Example I have made the response middleware like this :-
module.exports = function(req, res, next) {
const message = {};
message.body = req.responseObject;
message.success = true;
message.status = req.responseStatus || 200;
res.status(message.status).send(message);
return next();
};
Above code will generate the format like this.
{
"success": true,
"status": 200,
"body": {
"name": "rahul"
}
}
You can use request uplifter property of express. You can add responseObject and responseStatus from previous middleware.
Errors can be made in separate middleware likewise.
You can call by this in your routes:-
const responseSender = require('./../middleware/responseSender');
/* your rest middleware. and put responseSender middleware to the last.*/
router.get('/',/* Your middlewares */, responseSender);
You can call it by:-
exports.groups_Get_All = (req, res, next) => {
Group.find()
.exec()
.then(docs => {
const response =
docs.map(doc => {
return {
gname: doc.gname,
employee: doc.employeeId,
_id: doc._id,
createdAt: doc.createdAt
};
})
req.responseObject = response; // This will suffice
return next()
})
.catch(next);
}
Post a Comment for "Proper Way To Return Json Format Using Node Or Express"