繁体   English   中英

收到状态为 200 且没有正文的 HTTP 请求

[英]HTTP request received with status 200 and without body

我正在使用 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))
            }
        }      
    })
});

你需要返回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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM