我正在尝试映射我的api响应以及处理所有错误

时间:2019-05-02 07:00:44

标签: reactjs

我正在尝试映射我的api响应并处理所有可能的错误情况,但是我需要优化和编写更复杂的react代码,因为我是新来响应的,请帮助重构代码:-

My code
        const response = fetch('http://localhost:8080/loginController', {
        mode: 'no-cors',
        method: 'POST',
        headers: {    
             "Access-Control-Allow-Origin": "*",
             "Content-Type": "application/json" },
        body: JSON.stringify(reqParams),
        }).then(handleResponse)
        .then(response => console.log("ok"))
        .catch(error => alert("Service is down "+error) );

         const user = await handleResponse(response);

        return await user;
    }

    async function handleResponse(response) {
     return await response
        .then(response => {  
            if(!response)  {
                return Promise.resolve(response)
            }        
            if ( !response.ok) {
                switch (response.status) {
                    case 400:
                        break;
                    case 401:
                        break;
                    case 404:
                        break;
                    case 500:
                        break;
                    default:
                        break;
                }
                const error = (response && response.message) || 
                               response.statusText;
                return Promise.resolve(error);
            }

             return response.json();
        });

0 个答案:

没有答案