Javascript 面对面-';Uncaught(in promise)SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符';
我使用事件函数postData()发送注册表数据,单击submit按钮时会触发该函数。在react代码中,我在register route发送用户数据。注释中还提到了行号-Javascript 面对面-';Uncaught(in promise)SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符';,javascript,json,reactjs,express,mern,Javascript,Json,Reactjs,Express,Mern,我使用事件函数postData()发送注册表数据,单击submit按钮时会触发该函数。在react代码中,我在register route发送用户数据。注释中还提到了行号- const postData = async(event) =>{ event.preventDefault(); const { name, email, phone, work, password, cpassword} = user; const response = a
const postData = async(event) =>{
event.preventDefault();
const { name, email, phone, work, password, cpassword} = user;
const response = await fetch('/register' , {
method: 'POST',
headers : {
"Content-Type" : "application/json"
},
body: JSON.stringify({
name: name,
email : email,
phone : phone,
work : work,
password: password,
cpassword : cpassword
})
});
console.log('1'); //line 44!!!!
const data = await response.json();
console.log('1'); //line 48
if(data){
console.log('1'); //line 51
window.alert("registration successful");
console.log("registration successful");
history.push('/login');
}else{ //line 57!!!!
console.log('1'); //line 58
window.alert("Invalid registration");
console.log("Invalid registration");
}
console.log('1'); //line 63
}
在我的express代码中,我将它存储在数据库中-
router.post('/register' , (req,res)=>{
const {name, email, phone, work, password, cpassword} = req.body;
//we are checking if any of the inputs are empty or not
if(!name || !email || !phone || !work || !password || !cpassword){
return res.status(422).send('Please Fill All The Fields');
}
//we are observing if a user already registered or not by checking it's email
User.findOne({email : email})
.then((userExist) =>{
if(userExist){
return res.status(422).send('Email already exists');
}else if(password !== cpassword){
return res.status(422).send('Passwords are not matching');
}
//if the email dont exist , that means the user is new and we will store it's data in the DB
const user = new User({
name : name,
email : email,
phone : phone,
work : work,
password : password,
cpassword : cpassword,
});
//saved the stored data in the DB
user.save()
.then(()=>{
res.status(201).send('User registered Successfully')
})
.catch((err)=>{
res.status(500).send(err);
})
}).catch((err)=>{
console.log(err);
})
})
我可以将用户数据存储在数据库中,但在控制台中看不到警报和控制台消息。我还使用useHistory钩子在注册后重定向到登录页,但没有重定向到登录页。在控制台中,我面临此错误,还添加了“console.log('1'))'来检查代码是否正在运行。但是在第44行控制台之后,我在第57行遇到了错误
我还在学习mern开发,所以我还是一个新手。请帮我解决这个问题。非常感谢。您可以在这里做两件事: 要么:
return res.status(422).send({message: 'Passwords are not matching'});
或
如果在前端使用第一个选项,则可以使用数据访问消息。消息发回类似“User registered Successfully”的字符串不是正确的JSON“用户注册成功”是正确的JSON@RexHenderson谢谢你,我今天得学点新东西。干得好,巴维斯!这就是所谓的一切!:)感谢您回答@voxtool,现在我明白我的错误了。非常感谢!
return res.status(422).json("Passwords are not matching");