【问题标题】:proper way to return json format using node or express使用 node 或 express 返回 json 格式的正确方法
【发布时间】:2019-02-18 09:31:56
【问题描述】:

我的问题实际上是从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);
});

上面的 sn-p 是我的 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(全局范围)的这种示例格式响应?

【问题讨论】:

  • 我用res.end(JSON.stringify(results));
  • 它只对数据进行字符串化。它没有给出正确的格式。

标签: javascript node.js mongodb express


【解决方案1】:

如果您使用的是快递,请不要从控制器发送消息。制作一个主要目的是向客户端发送响应的中间件。这将使您能够设置 consist 响应客户端的格式。

例如,我制作了这样的响应中间件:-

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);
}

【讨论】:

  • 如何从每个api调用这个中间件?
  • 请再次检查答案。我已经编辑了答案。
  • 在实现你的代码 sn-p 之后,我得到 { "success": true, "status": 200 } 但不是数据。我需要与此响应一起显示数据。
  • 您发送了两次响应。只发送一次响应。 res.send() 应该在你的路由生命周期中被调用一次。
  • req.responseStatus = 响应;你的意思是 req.responseObject ?我说的对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多