[英]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.