Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS Fetch Returns Empty Response but Postman Does Not

I have a React JS application that is trying to log in to a token-based API (that I am also developing, using Laravel 5.5 and Laravel Passport). I'm trying to implement the basic login (login using a username and password, receive a token from the server once verified, use that token for future queries).

The code I'm using to fetch is below:

function loginApi(username, password) {
    return fetch(loginUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            grant_type: 'password',
            client_id: clientId,
            client_secret: clientSecret,
            username: username,
            password: password
        })

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

It's worth noting it's not entirely complete, as I'm currently just trying to determine the response I'm getting back.

I've already solved the normal issues one encounters, like CORS problems, however the issue I'm encountering now is that the response from the API is just... empty. Even in the Network tab of Chrome's developer tools, if I inspect the request directly, the response is empty.

dev tools 1

dev tools 2

However, if I make the exact same query with Postman, the results are exactly what I expect.

postman

What could be the issue here? Why would the exact same query return different results?

like image 543
CGriffin Avatar asked Dec 11 '22 10:12

CGriffin


1 Answers

.json is a function and needs to be invoked. Try..

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

You're currently returning the .json parsing function.

like image 61
D. Walsh Avatar answered Feb 27 '23 02:02

D. Walsh