How can i get errors value inside Promise object which return from Fetch Api?

人盡茶涼 提交于 2019-12-06 09:41:09
Sam

To get the error from the promise, you can do it like this:

promise.then(function(data) {
  }, function(error) {...}

OR

To got promise error you can also use .catch() block

 .then(){...}
 .catch(){..}

Never going to this part because server already sent the response

.then(function(response) {
            console.log(response);
            console.log(response.json());

            // not working never go into this function
            response.json().then(function(value) {
                console.log('access promise');
                console.log(value); // "Success"
            });

You can write your code in this way:

fetch(deafaultUrl + '/v1/users/', {
        headers: {
            'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(userInfoParams)
    })
    .then(function(response) {
        // if request is successful
    }
    .catch(err){
         // if got error
     }
    });

Here is the documentation of then(...)

You should use it like this :

p.then(function(value) {
   // fulfillment
  }, function(reason) {
  // rejection
});

Then your code will look like this

fetch(deafaultUrl + '/v1/users/', {
        headers: {
            'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(userInfoParams)
    })
    .then(function(response) {
        //Land here if request is successful
        console.log(response);

        if (response.status !== 200 && response.status !== 201) {
            throw new Error("Bad response from server");
        }
    }, function(error){
        //Land here if request has an error
        console.log(error);
    });

I found the solution that response.json() can only read once if i get of console.log(response.json()); it works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!