我的问题实际上是复制自使用 Node 或 Express 返回 JSON 的正确方法 https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express。
我需要这种格式的回复。
响应 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(全局范围)实现此示例格式响应?