简体   繁体   English

如何访问 req.body 的特定部分(Node JS)

[英]How to access a specific part of req.body (Node JS)

I have been trying to specific access a nested property of req.body the output however is always undefined the code is as follows我一直在尝试特定访问 req.body 的嵌套属性 output 但是始终未定义代码如下

  let dataRecieved = JSON.stringify(req.body);
        console.log(dataRecieved);
        let refCode = dataRecieved["refferal"];

and the output in the terminal is终端中的 output 是

{"name":"","phone":"","emailid":"","refferal":"gg","time":"Sat Oct 05 2019 08:14:07 GMT+0530 (India Standard Time)"}
undefined

the second undefined is when i ask for the refferal object of req.body第二个未定义是当我要求 req.body 的参考 object

First mistake you made is converting the JSON object into a string.您犯的第一个错误是将 JSON object 转换为字符串。 One way you can access data inside a JSON object using.您可以使用一种方法访问 JSON object 中的数据。 operator.操作员。 Therefore try below code snippet to access data inside the object.因此,请尝试下面的代码片段来访问 object 中的数据。

let dataRecieved = req.body;
console.log(dataRecieved.name);

Considering the best practices either you can lodash (https://lodash.com/ ) or object destructuring (ES6 destructuring) based on the scenario.考虑到最佳实践,您可以根据场景使用 lodash (https://lodash.com/ ) 或 object 解构(ES6 解构)

make sure body-parser middleware is installed确保安装了body-parser中间件

const app = require('express')()
const bodyParser = require('body-parser')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

after that you can access req.body directly as a object之后,您可以直接访问req.body作为 object

app.post('*' (res, req) => {
  let dataRecieved  = req.body
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM