Node js Express js如何在POST方法rawbody中访问json对象

时间:2017-05-10 11:02:20

标签: javascript json node.js express

如何从rawbody请求数据,如JSON对象所示。

这是我在rawbody See this Picture if you can't understand

中的JSON值
{
 "startdate" : "2017-05-28T09:00:00+05:30",
 "endddate" : "2017-05-28T09:30:00+05:30",
 "event" : "Meeting",
 "type" : 
   [
    "pickup" , "drop"
   ],
 "details" : 
   {
    "name" : "Zhunki",
    "address" : "madras",
    "from" : "vergeenia",
    "to" : "malpur"
   }
}

现在我希望从详细信息对象中获取类型数组中的事件删除名称地址

My Express js Code是:

app.post('/trip' , function(req , res){
    var event = req.rawBody.event; 
    var type = req.rawBody.type; 
    var name = req.rawBody.name;
    var address = req.rawBody.address;

    var jsonresult = {
         status : 'ok',
         message : event + 'Created Successfully'
       };
    res.json([json]);

})

请帮帮我......谢谢

2 个答案:

答案 0 :(得分:1)

rawBody将原始。这将是浏览器发送的内容。它不会被解析。

你需要解析它。您可以使用JSON.parse,但使用JSON body parser可能会更好。

答案 1 :(得分:1)

您可以要求body-parser并使用已解析的req.body

请记住npm install body-parser

 const bodyParser = require('body-parser');

 app.use(bodyParser.json());

 app.post('/trip' , function(req , res){
    var event = req.body.event; 
    var type = req.body.type; 
    var name = req.body.details.name;
    var address = req.body.details.address;

    var jsonresult = {
        status : 'ok',
        message : event + 'Created Successfully'
    };
    res.json([json]);

});