我是React和NodeJS express编程的新手,我被一些错误困扰了好几个小时。当我尝试抓取时,有时我得到一个响应(但不是我的响应),有时我得到'failed to fetch‘。
我试图在没有太多理解的情况下理解“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'
});
}
});
我很困惑,希望你能帮助我。谢谢。
发布于 2018-08-10 16:12:32
您没有正确访问响应的JSON。您需要调用响应的Body#json
方法来实际访问JSON内容。另请注意,它返回一个解析为响应的JSON内容的promise:
fetch('…', { … })
.then(res => res.json())
.then(json => {
console.log(json.msg);
});
此外,我建议将HTTP状态代码与JSON一起发送,而不是使用ok
属性。这是一种标准方式,并通过Response
对象提供了内置支持:
res.status(200).json({ … });
https://stackoverflow.com/questions/51790028
复制