【发布时间】:2019-03-12 01:32:59
【问题描述】:
我正在制作带有 React、Node 和 MySQL 身份验证的小型 CRUD 应用程序。 所有这一切的初学者。因此,我从后端获取数据,在客户端收到状态为 200 的数据,但正文为空。在 Chrome 开发人员工具的网络选项卡中,我看到收到的数据作为响应。前端后端DB都在一台机器上 代码:
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))
}
}
})
});
【问题讨论】:
-
您是说在 Chrome 网络选项卡中看到数据,但在您的代码中它是空的?
console.log(response)显示什么? -
那你为什么要做2。在第二个中,响应将是未定义的
-
响应正文:(...) bodyUsed:true headers:Headers {} ok:true redirected:false status:200 statusText:"OK" type:"cors" url:"localhost:4000/…" proto:Response -- 这是显示。 @Tarek Essam:问题是第一个响应不包含正文。服务器返回预期的结果,我用来自服务器的代码更新了帖子。
-
@Henry Woody:服务器返回了预期的结果,我用来自服务器的代码更新了帖子
-
根据你放在那里的内容,@Scott 的回答是正确的,基本上你是在响应上调用
.json(),然后丢弃结果。在解释console.log的输出时,尤其是涉及到对象时,请记住在调用它和写入它之间可能存在延迟;在这种情况下,响应中表明其主体已被消耗的任何内容都将来自在调用.json()之后。
标签: javascript node.js reactjs