7

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?

2 Answers 2

11

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

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

You're currently returning the .json parsing function.

Sign up to request clarification or add additional context in comments.

2 Comments

D'oh! Thanks, that was it. I am curious however: why would invoking that function change the response from the server? To my admittedly new-to-React mind, the response from the server should be the same regardless, no? The only difference being how its then understood by the application? Why would viewing the response in the network tab be empty?
@PeregrineStudios you're not changing the server response. Remember that fetch is now a browser native API. You may be thinking about an AJAX call that the browser gets and returns, but then how you format it is your business. But with Fetch, the entire promise chain is part of the API call. It "fetched" the call correctly (your server logs should show that) but didn't show in the developer console because the browser interprets the entire fetch call, not just the wire request.
3

I've succeeded to fix it this way:

client-side (using React and Fetch-API)

const update = async (credentials, productData) => {
  try {
    let response = await fetch('/api/products/', {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + credentials.t
      },
      body: productData
    })
    return await response.json()
  } catch (err) {
    console.log(err)
  }
}

server-side (Nodejs, Express with ):

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
...

1 Comment

NOTE: it won't work without 'Content-Type': 'application/json' on the client-side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.