-1

I'm a bit stuck with the fetch API. This is a simple Login function

export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}

When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?

Thank you!

  • Your server doesn't like the request you're sending. – James Feb 09 '22 at 15:52
  • *"When user is not found the in the backend return 400 bad request"* It really shouldn't do that. It should return [401](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401). – T.J. Crowder Feb 09 '22 at 15:53
  • Ok about the return status, but I'm not able to return the json object or the status code – Old-fashioned-dev Feb 09 '22 at 15:55
  • @Old-fashioned-dev - On a successful response, your code is returning the result of parsing the JSON from the server. Are you saying you're not seeing that? – T.J. Crowder Feb 09 '22 at 16:00
  • (Reading a bit between the lines, you *might* be having an issue with the fact that `loginUser` returns a promise. If so, these may help: [1](https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise), [2](https://stackoverflow.com/questions/51338277/async-function-returning-promise-instead-of-value), [3](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)) – T.J. Crowder Feb 09 '22 at 16:02

2 Answers2

0

How can I return the json object or the response status?

The ok response property gives you the high-level "worked/didn't work" for the HTTP call (fetch only rejects its promise on network errors, not HTTP errors — a footgun in the api you constantly see people falling afoul of).

I wouldn't return the response status, I'd include it in an error thrown by the async function. I typically do that like this:

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`};
        }
        return response.json();
    }); // Note: No `catch` here!
}

But if you really want to return it:

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            return {failed: true, status: response.status};
        }
        return response.json();
    })
    .catch(e => console.log(e));
}

Turning rejections into fulfilments that way is generally not best practice, though.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-3
    .then(res=>{
    if(res.ok)
    {
       return response.json()
    }
    else{
    // return 400 bad request here
    }
    })
  • 2
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Feb 15 '22 at 09:24