簡體   English   中英

如何將新的 Object 添加到空數組並在終端中顯示

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

誰能幫我弄清楚如何將 newUser Object 添加到一個名為 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.`);
     }
   });

來自快遞文件

請求正文

包含在請求正文中提交的數據鍵值對。 默認情況下,它是未定義的,並且在您使用諸如 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.`);
     }
   });

這是您在repl.it上的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM