简体   繁体   English

如何将新的 Object 添加到空数组并在终端中显示

[英]How to add a new Object to an empty array and display it in the terminal

Can anyone help me figure out how to add newUser Object to an empty array called users?谁能帮我弄清楚如何将 newUser Object 添加到一个名为 users 的空数组中? The data I send using the POSTMAN inside of req.body is not displayed in the terminal when I run console.log(users)当我运行 console.log(users) 时,我使用 req.body 内部的 POSTMAN 发送的数据未显示在终端中

   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") {

       let requestBody = "";
       req.on("data", (addUser) => {
         requestBody += addUser;
       });
       req.on("end", () => {
         requestBody = JSON.parse(requestBody);
         let newUser = {
           "username": requestBody.username,
           "password": requestBody.password
         }
         users.push(newUser);
         console.log(users);
       });

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

From the express documentation来自快递文件

req.body请求正文

Contains key-value pairs of data submitted in the request body.包含在请求正文中提交的数据键值对。 By default, it is undefined, and is populated when you use body-parsing middleware such as express.json()默认情况下,它是未定义的,并且在您使用诸如 express.json() 之类的正文解析中间件时填充

So you'll need to do this somewhere at the top of your file,所以你需要在文件顶部的某个地方执行此操作,

app.use(express.json);

Also, with express, you don't need to use req.on to parse incoming data, you can simply do the following,另外,使用 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.`);
     }
   });

Here's your example on repl.it这是您在repl.it上的示例

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

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