[英]Proper way to send JSON data along with sendFile() with Node.js and Express
[英]proper way to return json format using node or express
我的问题实际上是从正确的方式复制的, 以使用node或Express返回JSON 。 我需要这种格式的回复。
响应API的样本格式
{
"success":true,
"code":200,
"message":"Ok",
"data": []
}
我遵循了以上问题中提供的所有方法,但仍然无法破解正确的答案。 由于我有很多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);
});
上面的代码段是我的app.js文件中的代码。 我的路线代码看起来像这样。
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
});
});
};
现在,我得到的只是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"
}
]
现在我的问题是如何对每个api(全局范围)实施这种示例格式响应?
如果您使用的是Express,请勿发送来自控制器的消息。 制作中间件的主要目的是将响应发送到客户端。 这将使您能够设置对客户端的包含响应格式。
例如,我制作了这样的响应中间件:-
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();
};
上面的代码将生成这样的格式。
{
"success": true,
"status": 200,
"body": {
"name": "rahul"
}
}
您可以使用express的request uplifter属性。 您可以从以前的中间件添加responseObject和responseStatus。
同样,在单独的中间件中也会出错。
您可以在您的路线中通过此电话致电:
const responseSender = require('./../middleware/responseSender');
/* your rest middleware. and put responseSender middleware to the last.*/
router.get('/',/* Your middlewares */, responseSender);
您可以通过以下方式致电:
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.