node.js - react & node API - 获取函数错误
问题描述
我只是 React 和 NodeJS 快速编程的新手,我在几个小时内都陷入了一些错误。当我尝试获取时,有时我得到了响应(但不是我的响应),有时我得到了“获取失败”。
我试图在没有太多理解的情况下理解“cors”概念,但我已经提交 app.use(cors()) 允许每个来源。
请注意,我的服务器有时会收到“OPTIONS”请求,有时会收到“POST”请求。
在我的 React 中,我有这个功能:
fetch('http://localhost:3000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify ({
user: this.state.username,
pass: this.state.password,
})
}).then(res => {
console.log(res.msg);
})
.catch(function(err) {
alert(err);
})
}
在我的 NodeJS 我有这个功能:
router.post('/', (req, res) => {
let user = {
username: req.body.user,
password: req.body.pass
}
UserModel.findOne({'username': user.username, 'password' : user.password}, function(err, user) {
if (err) {
res.json({
ok: false,
msg: 'login failed, try later'
});
} else if (user) {
let token = jwt.encode(user, secret);
res.json({
msg: 'logged in',
ok: true
});
} else {
res.json({
ok: false,
msg: 'invalid input'
});
}
});
我很困惑,希望你能帮助我。谢谢。
解决方案
您没有正确访问响应的 JSON。您需要调用Body#json
响应的方法才能真正访问 JSON 内容。另请注意,它返回一个解析为响应的 JSON 内容的承诺:
fetch('…', { … })
.then(res => res.json())
.then(json => {
console.log(json.msg);
});
另外,我建议将 HTTP 状态代码与 JSON 一起发送,而不是使用ok
属性。Response
这是一种标准方式,并且通过对象具有内置支持:
res.status(200).json({ … });
推荐阅读
- swift - 如何从结构中获取随机值
- ios - 自定义后退按钮比原生后退按钮慢很多
- r - ggplot2:用 geom_col() 覆盖 stat_function()
- mysql - docker-compose + spring-boot + mysql = CommunicationsException:通信链接失败
- c# - 鉴于属性名称是动态的,如何使用 linq 对动态对象列表进行分组?
- mysql - Nested select MAX() of another table when data doesn't exist
- ruby-on-rails - 有没有办法使用工作的“rails c”控制台查看视图?
- c# - 由于异常而扰乱函数调用顺序
- python - 找到离点最近的多边形的快速方法
- ms-word - 当 Word 2010 出现“未指定错误”时,会显示部件和行号。如何在 Word 2019 中显示此信息?