首页 > 解决方案 > 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);
        });
});
});

我正在处理登录表单,我的后端工作正常,但是在 react native 上运行时出现错误 JSON Parse error: Unexpected identifier "Not".is it a json error 吗?

标签: node.jsmongodbreact-native

解决方案


看起来问题是当您在未找到用户的情况下传递“未找到”时,即使是“成功”

在 UI 方面,当您调用.then((response)=>response.json())它时,它会尝试将响应更改为 json 格式,而您的 API 正在返回不符合 json 结构的字符串“未找到”。

至于解决方案,您可以在所有场景中传递 JSON,您可能需要相应地更改您的 UI。

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);
        });
});
});

推荐阅读