最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JSON解析错误:意外的标识“未找到”

运维笔记admin13浏览0评论

JSON解析错误:意外的标识“未找到”

JSON解析错误:意外的标识“未找到”

 fetch('http://192.168.120.100:8080/login', {
    method: 'POST',
    body: JSON.stringify(SignInData),
    headers: {
      'Content-Type': 'application/json'
    }
  })
   .then((response)=>response.json())
    .then((user)=>{
      if(user.status=="success"){
        alert("success")
        console.log("success");

      }else{
      alert("error")
      console.log("fail");
      }

    })
    .catch((error)=>{
      console.log("Error, with message::",error)
    });
  }

和我的服务器代码

   router.post('/login', function (req, res) {
   User.findOne({ email: req.body.email }).then((user) => {
        console.log('testing' + JSON.stringify(user));
        if (!user) return res.status(404).send("Not found");
        //check password matches
        if (user.password == req.body.password) {
            user.status = "Success";
            res.status(200).send('success');
        } else {
            res.status(404).send('Invalid Password');
        }
    })
        .catch((err) => {
            res.status(500).send(err);
        });
});
});

我工作的登入形式和我的后端工作正常,但在运行上反应原生我收到一个错误JSON解析错误:意外的标识符“不”。是它一个JSON错误?

回答如下:

貌似问题是,当你路过的“未找到”的情况下,用户没有找到,那么对于这个问题,即使“成功”

在当你调用.then((response)=>response.json())的UI端其试图改变成JSON格式的响应,而您的API将返回字符串“未找到”,这不符合JSON结构。

作为解决方案,您可以在所有情况下通过JSON,您可能需要相应地更改用户界面。

router.post('/login', function (req, res) {
   User.findOne({ email: req.body.email }).then((user) => {
        console.log('testing' + JSON.stringify(user));
        var result = {};
        if (!user) {
           result.message = "Not Found"
           return res.status(404).send(result);
        }
        //check password matches
        if (user.password == req.body.password) {
            user.status = "Success";
            result.message = "Success"
            res.status(200).send(user);
        } else {
            result.message = "Invalid Password";
            res.status(404).send(result);
        }
    })
        .catch((err) => {
            res.status(500).send(err);
        });
});
});
发布评论

评论列表(0)

  1. 暂无评论