node.js - 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 吗?
解决方案
看起来问题是当您在未找到用户的情况下传递“未找到”时,即使是“成功”
在 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);
});
});
});
推荐阅读
- javascript - 如何从 node.js 中的用户列表中排除最近添加的用户
- reactjs - 具有可选/条件状态提升的 Reactjs 组件
- sql - 使用此掩码将 int 转换为日期:DD/MM/YYYY
- mongodb - MongoDB Atlas mongorestore 连接失败及时响应
- java - 如何在 JUnit 的不同线程中运行单元测试和集成测试?
- memory-leaks - React 的 useState 泄漏
- php - Prestashop 为 symfony 创建的管理控制器生成了错误的令牌
- excel - 从工作表导航到编辑栏的快捷方式/快捷方式
- bazel - 如何从 repository_ctx 运行 bazel 二进制可执行文件
- python - 默认和计算在甘特视图odoo14中不起作用