微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

面对 - '未捕获承诺SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的意外字符'

如何解决面对 - '未捕获承诺SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的意外字符'

我正在使用事件函数 postData() 发送我的注册表单数据,该函数在单击提交按钮时被触发。在反应代码中,在注册路由中,我正在发送用户数据。还在评论中提到了行号 -

   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

}

在我的快递代码中,我将它存储在数据库中 -

router.post('/register',(req,res)=>{

const {name,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,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 行的错误

enter image description here

我还在学习开发开发,所以我还是个新手。请帮我解决这个问题。非常感谢。

解决方法

您可以在这里做两件事:

要么:

return res.status(422).send({message: 'Passwords are not matching'});

return res.status(422).json("Passwords are not matching");

如果您在前端使用第一个选项,您可以使用 data.message

访问消息

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。