简体   繁体   中英

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? The data I send using the POSTMAN inside of req.body is not displayed in the terminal when I run console.log(users)

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

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,

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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