miodragdz
miodragdz

Reputation: 11

HTTP request received with status 200 and without body

I am making small CRUD app with authentication in React, Node and MySQL. Beginner in all of this. So, I fetch the data from back-end, received on client side with status 200, but body is empty. In Chrome developer tools, network tab, I see data received in response. Front-end, back-end and DB are all on one machine Code:

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());
            }

Server:

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))
            }
        }      
    })
});

Upvotes: 1

Views: 3012

Answers (1)

Scott
Scott

Reputation: 3765

You need to return response.json() so that your next then can receive it. Change this:

.then(response => {
    console.log(response)
    response.json()
})

To:

.then(response => {
    return response.json()
})

Or even shorter as:

.then(response => response.json())

UPDATE: After seeing your server code, there's another thing you can try. You need to ensure you are responding with JSON. Here, try changing this line:

 res.send(result)

To:

 return res.json(result);

Upvotes: 2

Related Questions