提问者:小点点

使用node或express返回json格式的正确方法


我的问题实际上是从使用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(全局范围)实现这个示例格式响应?


共1个答案

匿名用户

如果您使用的是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);
}