can't get response status code with JavaScript fetch [duplicate] can't get response status code with JavaScript fetch [duplicate] reactjs reactjs

can't get response status code with JavaScript fetch [duplicate]


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`, {    withCredentials: true,    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 little blog.


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.