can't get response status code with JavaScript fetch

74,796

Solution 1

The status code is the status property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok flag) before calling json:

fetch(`${baseUrl}api/user/login`, {
    credentials: "include", // ¹ See note below
    headers: myHeaders
})
.then(function(response) {
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
})
.then(// ...

Not checking that the request succeeded is such a common mistake I wrote it up on my anemic old blog.


¹ You had withCredentials: true, but the documentation says it's credentials: "include". (Thank you aderchox for pointing that out.)

Solution 2

The status is present in the response object. You can get it inside your first then block

.then(function (response) {
    console.log(response.status);
    return response.json();
})

Since you are returning response.json(), the subsequent then and catch only gets the result of response.json() which is the body of the response.

Share:
74,796

Related videos on Youtube

ali mottaghian
Author by

ali mottaghian

Updated on April 22, 2022

Comments

  • ali mottaghian
    ali mottaghian over 1 year

    I'm trying to create a login form. when I'm testing the service with Postman, I will get a body object with status code and etc.

    Postman Result

    But, with JavaScript fetch, I can't get body object and I just received an error:

    fetch console log

    export const login = (username,password) => {
        return dispatch=>{
            const basicAuth = 'Basic ' + btoa(username + ':' + password);
            let myHeaders = new Headers();
                myHeaders.append('Authorization', basicAuth);
                myHeaders.append('Content-Type', 'application/json');      
                fetch(`${baseUrl}api/user/login`, {
                    withCredentials: true,
                    headers: myHeaders
                })
                .then(function (response) {
                    return response.json();
                })
                .then(function (json) {
                    dispatch(setLoginInfo(json))
                })
                .catch(err =>{
                    console.log(err)
                     dispatch(loginFailed())
                });
        }
    
    }
    

    I need to get status code in fetch.

    • 04FS
      04FS over 4 years
      You got a CORS error here … so go read up on what that means, and what needs to be done to fix it.
    • Mafei
      Mafei over 2 years
      I put the answer here please check. stackoverflow.com/a/66940824/12553450
    • Lepy
      Lepy almost 2 years
      you can try this: async function fetchText() { let response = await fetch('url.php'); console.log(response.status); // 200 console.log(response.statusText); // OK if (response.status === 200) { let data = await response.text(); console.log(data); } }
  • ali mottaghian
    ali mottaghian over 4 years
    when my request gets failed, nothing in .then() will run. it goes straight to catch()
  • ali mottaghian
    ali mottaghian over 4 years
    when my request gets failed, nothing in .then() will run. it goes straight to catch()
  • T.J. Crowder
    T.J. Crowder over 4 years
    @alimottaghian - The promise from fetch only rejects on network errors, not HTTP errors. So it will reject if you can't send the request to the server, but it does not reject if the server responds with (say) a 404.
  • Mario Gonzales Flores
    Mario Gonzales Flores over 4 years
  • T.J. Crowder
    T.J. Crowder over 4 years
    @MarioGonzalesFlores - Wow, a lot of the Response object is missing in Safari (link), including really basic things like ok (and as you pointed out, status). That's outrageous. It would be better not to support fetch at all. How are people supposed to know if the fetch worked?!
  • T.J. Crowder
    T.J. Crowder over 4 years
    @MarioGonzalesFlores - I can't speak for Safari on Mac OS, but unfortunately MDN is just wrong about iOS Safari. It has both ok and status, at least as of iOS v12.3.1. I've filed an issue.
  • Nicolas Silva
    Nicolas Silva over 3 years
    you can try return response.text() instead, i got exactly the same issue, going directly to catch then i realize ir was the response
  • Mafei
    Mafei over 2 years
  • Lepy
    Lepy almost 2 years
    @MarioGonzalesFlores try this with async: fetch('siteLink.php') .then(async res => { console.log(res.status); })
  • aderchox
    aderchox over 1 year
    With ES6 fetch use: credentials: 'include' and not withCredentials: true.
  • T.J. Crowder
    T.J. Crowder over 1 year
    @aderchox - Thanks for pointing that out! I just copied what the OP had, but you're right. I've flagged that up in the answer as well. (Side note: fetch has nothing to do with "ES6", it's the web platform, not JavaScript.)