简体   繁体   English

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

[英]proper way to return json format using node or express

My question is actually copied from Proper way to return JSON using node or Express . 我的问题实际上是从正确的方式复制的, 以使用node或Express返回JSON I need the response in this format. 我需要这种格式的回复。

Sample format for response API 响应API的样本格式

{
"success":true,
"code":200,
"message":"Ok",
"data": []
}

I followed all the methods provided in the above question, but still i couldn't crack the right answer. 我遵循了以上问题中提供的所有方法,但仍然无法破解正确的答案。 since i have many apis, i need this response format for every api. 由于我有很多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);
});

the above snippet is of my app.js file. 上面的代码段是我的app.js文件中的代码。 And my route code looks somethig like this. 我的路线代码看起来像这样。

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

Right now im getting response of just plain data in json format. 现在,我得到的只是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"
    }
]

Now my question is how to implement this sample format response to every api(global scope)? 现在我的问题是如何对每个api(全局范围)实施这种示例格式响应?

If you are using express, don't send the message from the controller . 如果您使用的是Express,请勿发送来自控制器的消息。 Make a middleware that's main purpose is to send the response to the client. 制作中间件的主要目的是将响应发送到客户端。 This will give you a power of setting the format of consist response to the client. 这将使您能够设置对客户端的包含响应格式。

For Example I have made the response middleware like this :- 例如,我制作了这样的响应中间件:-

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

Above code will generate the format like this. 上面的代码将生成这样的格式。

{
  "success": true,
  "status": 200,
  "body": {
    "name": "rahul"
  }
}

You can use request uplifter property of express. 您可以使用express的request uplifter属性。 You can add responseObject and responseStatus from previous middleware. 您可以从以前的中间件添加responseObject和responseStatus。

Errors can be made in separate middleware likewise. 同样,在单独的中间件中也会出错。

You can call by this in your routes:- 您可以在您的路线中通过此电话致电:

const responseSender = require('./../middleware/responseSender');
 /* your rest middleware. and put responseSender middleware to the last.*/
router.get('/',/* Your middlewares */, responseSender);

You can call it by:- 您可以通过以下方式致电:

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.

相关问题 使用Node.js和Express将JSON数据与sendFile()一起发送的正确方法 - Proper way to send JSON data along with sendFile() with Node.js and Express 在Express / Jade中插值JSON的正确方法? - Proper way to interpolate JSON in Express/Jade? 使用节点以javascript格式将.json格式的html格式数据保存在.json文件中 - Save html-form data in json format in a .json file using node and express with javascript 节点/ Express API路由中正确且可持续的错误处理方式 - Proper & Sustainable way of Error Handling in Node/Express API Routes 在 node/express 中解析布尔查询字符串参数的正确方法 - Proper way to parse Boolean query string param in node/express 在 node.js express 中返回响应的正确方法是什么? - What is the proper way of returning responses in node.js express? 从MVC控制器返回Json但在javascript中日期格式不正确 - Return Json from MVC controller but Date format not proper in javascript 使用 Node 中另一个发布数据的返回值发布数据的标准方法是什么 - Express / FaunaDB - What's the standard way to post data using a return value from another post data in Node - Express / FaunaDB 有没有办法使用节点 js 从 pug js 表单返回多个错误并表达 - Is there a way to return multiple errors from a pug js form using node js and express Want to call an api to get the data from mongodb in json format but getting in raw format, using javascript, node.js, express, mongodb - Want to call an api to get the data from mongodb in json format but getting in raw format, using javascript, node.js, express, mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM