[英]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.