Javascript 如何将新对象添加到空数组并在终端中显示

Javascript 如何将新对象添加到空数组并在终端中显示,javascript,node.js,express,Javascript,Node.js,Express,有人能帮我弄清楚如何将newUser对象添加到名为users的空数组中吗?当我运行console.log(users)时,在req.body内部使用邮递员发送的数据不会显示在终端中 从快车上 要求正文 包含请求正文中提交的数据的键值对。默认情况下,它是未定义的,并且在使用主体解析中间件(如express.json()时填充 所以你需要在文件顶部的某个地方这样做 app.use(express.json); 此外,使用express,您无需使用req.on解析传入数据,只需执行以下操作:

有人能帮我弄清楚如何将newUser对象添加到名为users的空数组中吗?当我运行console.log(users)时,在req.body内部使用邮递员发送的数据不会显示在终端中

从快车上

要求正文

包含请求正文中提交的数据的键值对。默认情况下,它是未定义的,并且在使用主体解析中间件(如express.json()时填充

所以你需要在文件顶部的某个地方这样做

app.use(express.json);
此外,使用express,您无需使用
req.on
解析传入数据,只需执行以下操作:

   let users = [];
   app.post("/signup", (req, res) => {
     let username = req.body.username;
     let password = req.body.password;
     /* typeof and undefined is added for the scenario 
        if the request body has either username or password object only;
        OR any isn't declared in the request body. */

     if (username !== null &&
       username !== "" &&
       typeof username !== "undefined" &&
       password !== null &&
       password !== "" &&
       typeof password !== "undefined") {

       users.push({
         username,
         password
       });
       console.log(users);

       res.send(`User ${username} successfully registered`);
     } else {
       res.send(`Please input both username and password.`);
     }
   });

以下是您在

上的示例,您能分享一下您是如何接受参数addUser的吗?在声明新用户之前,请尝试记录requestBody。您好,是的。我发现req.on对于express.js不是必需的,我在学习node.js时使用了它,而且由于express.js使一切变得更简单,所以我决定在if语句中直接声明
push()
。但是使用上面的例子会出现一个错误,因为newUser没有定义,所以我必须在
push()
之前声明这一点,让newUser={“username”:req.body.username,“password”:req.body.password}
感谢您的回复:)@jcpurfect是的,很抱歉这是一个打字错误,修复了。
   let users = [];
   app.post("/signup", (req, res) => {
     let username = req.body.username;
     let password = req.body.password;
     /* typeof and undefined is added for the scenario 
        if the request body has either username or password object only;
        OR any isn't declared in the request body. */

     if (username !== null &&
       username !== "" &&
       typeof username !== "undefined" &&
       password !== null &&
       password !== "" &&
       typeof password !== "undefined") {

       users.push({
         username,
         password
       });
       console.log(users);

       res.send(`User ${username} successfully registered`);
     } else {
       res.send(`Please input both username and password.`);
     }
   });