【发布时间】:2020-12-21 20:55:38
【问题描述】:
我正在尝试使用NODE.JS、express 和axios 为项目创建我的第一个 API。
当我尝试从终端使用node app.js(app.js 是服务器文件)时,一切都很好,所以我使用node cli.js 启动 CLI,我在其中输入日期,如电子邮件、用户名、密码 ecc ..
当服务器接受用户的请求时,它会抛出这个错误:
这是服务器代码(app.js)的一部分:
var users = require('./users.json');
{console.log(req.body);
if(req.body.new_password === req.body.new_password_confirm && req.body.new_email === req.body.new_email_confirm ){
let user = users.find((item )=>{ //<---- the method "find" who generate error
return item.username === req.body.new_username || item.email === req.body.new_email;
});
if(!!user){
res.send("email o username già in uso");
}else
if(!!user == false){
res.status(200).send("utente aggiunto");
let user_json = JSON.stringify(req.body);
fs.writeFileSync('users.json', user_json);
}
}else
res.status(200).send("email o password errati");
});`
这是客户端代码(cli.js)的一部分:
axios
.post("http://localhost:8080/", answers)
.then((response) => {
if (response.data) {
var registration_data = [
{
type: "input",
name: "new_email",
message: "email:",
},
{
type: "input",
name: "new_email_confirm",
message: "confirm email:",
},
{
type: "input",
name: "new_username",
message: "username:",
},
{
type: "password",
name: "new_password",
message: "password:",
mask: "*",
},
{
type: "password",
name: "new_password_confirm",
message: "confirm password:",
mask: "*",
},
];
inquirer.prompt(registration_data).then(async (answers) => {
console.log("\nTrying Validation... ");
axios
.post("http://localhost:8080/new_user", answers)
.then((response) => {
console.log(response.data);
});
});
} else if (!response.data) {
console.log("TODO: LOGIN");
}
})
.catch((response) => {
console.error(response);
});
IDK 为什么错误说 .find 实际上不是函数。
【问题讨论】:
-
上线之前你访问
users,为什么不记录一下,看看里面是否包含你认为包含的内容 -
假设
users是JSON,它不能包含任何函数。 -
.find是一个有效的函数,如果 JSON 包含一个数组 -
No
JSON如果没有被解析成有效的 JS 对象,它将无法工作..
标签: javascript node.js api express axios