我正在使用React,Node和MySQL中的身份验证来制作小型CRUD应用。 所有这方面的初学者。因此,我从后端获取状态为200的客户端接收的数据,但主体为空。在Chrome开发人员工具的“网络”标签中,我看到了收到的响应数据。前端,后端和数据库都在一台机器上 代码:
return fetch(`http://localhost:4000/authenticate?email=${email}&password=${password}`)
.then(response => {
console.log(response)
response.json()
})
.then(response => {
console.log(response)
// login successful if there's a id in the response
if (response.id) {
// store user details in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(response));
dispatch(success(response));
dispatch(alertActions.clear());
history.push('/');
} else {
dispatch(failure(response.message));
dispatch(alertActions.error(response.message));
//dispatch(logout());
}
服务器:
app.get('/authenticate', (req, res) => {
let answer = { message: ''}
let sql = `SELECT * FROM users WHERE email = '${req.query.email}'`;
console.log(sql)
let query = db.query(sql, (err, result) => {
console.log(result)
if(err) {
throw err
} else {
if (result.length > 0) {
if (result[0].password === req.query.password) {
res.send(result)
} else {
answer.message = 'Email and Password does not match!'
console.log(answer)
console.log(JSON.stringify(answer))
res.send(JSON.stringify(answer))
}
} else {
answer.message = 'Email does not exists!'
res.send(JSON.stringify(answer))
}
}
})
});
答案 0 :(得分:1)
您需要返回response.json()
,以便您的下一个then
可以收到。更改此:
.then(response => {
console.log(response)
response.json()
})
收件人:
.then(response => {
return response.json()
})
或更短为:
.then(response => response.json())
更新:看到服务器代码后,您可以尝试另一件事。您需要确保您使用JSON进行响应。在这里,尝试更改此行:
res.send(result)
收件人:
return res.json(result);