[英]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 . 我的问题实际上是从正确的方式复制的, 以使用node或Express返回JSON 。 I need the response in this format.
我需要这种格式的回复。
Sample format for response API 响应API的样本格式
{
"success":true,
"code":200,
"message":"Ok",
"data": []
}
I followed all the methods provided in the above question, but still i couldn't crack the right answer. 我遵循了以上问题中提供的所有方法,但仍然无法破解正确的答案。 since i have many apis, i need this response format for every api.
由于我有很多API,因此每个API都需要这种响应格式。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "POST, DELETE, GET");
return res.status(200).json({});
}
next();
});
app.use("/api", employeeRoutes);
app.use("/api", groupRoutes);
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
the above snippet is of my app.js file. 上面的代码段是我的app.js文件中的代码。 And my route code looks somethig like this.
我的路线代码看起来像这样。
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
};
})
res.send((response));
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
Right now im getting response of just plain data in json format. 现在,我得到的只是json格式的纯数据的响应。
[
{
"gname": "wordpres",
"employee": [
"5c6568102773231f0ac75303"
],
"_id": "5c66b6453f04442603151887",
"createdAt": "2019-02-15T12:53:25.699Z"
},
{
"gname": "wordpress",
"employee": [
"5c6568102773231f0ac75303"
],
"_id": "5c66cbcf1850402958e1793f",
"createdAt": "2019-02-15T14:25:19.488Z"
}
]
Now my question is how to implement this sample format response to every api(global scope)? 现在我的问题是如何对每个api(全局范围)实施这种示例格式响应?
If you are using express, don't send the message from the controller . 如果您使用的是Express,请勿发送来自控制器的消息。 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. 您可以使用express的request uplifter属性。 You can add responseObject and responseStatus from previous middleware.
您可以从以前的中间件添加responseObject和responseStatus。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.