Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'

前端 未结 5 1889
南旧
南旧 2020-11-22 07:19

I tried a ReactJS fetch call to a REST-API and want to handle the response. The call works, i get a response, which i can see in Chrome Dev Tools:

function g         


        
5条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:41

    In your then you should check if the response is OK before returning response.json:

    .then(function (response) {
        if (!response.ok) {
            return Promise.reject('some reason');
        }
    
        return response.json();
    
    })
    

    If you want to have the error message in your rejected promise, you can do something like:

    .then(function (response) {
        if (!response.ok) {
           return response.text().then(result => Promise.reject(new Error(result)));
        }
    
        return response.json();
    })
    

提交回复
热议问题