Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 575
ali mottaghian Avatar asked Feb 27 '19 08:02

ali mottaghian


People also ask

How do I get response status code on Fetch?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

How do I get response JSON from Fetch?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.

What is fetch () in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise. Syntax: fetch('url') //api for the get request .

What is failed fetch error?

The "TypeError: Failed to fetch" occurs for multiple reasons: An incorrect or incomplete URL has been passed to the fetch() method. The server you are making a request to does not send back the correct CORS headers. A wrong protocol is specified in the url.


2 Answers

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.)

like image 100
T.J. Crowder Avatar answered Oct 22 '22 05:10

T.J. Crowder


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.

like image 33
Panther Avatar answered Oct 22 '22 07:10

Panther