0

I am using fetch to post data on backend. Every time, it is success but sometimes it caught error The data was posted but still error is shown.

I am fetching by code : - Compose.js

fetch(`${props.url}/addBalance`, {
                method: 'POST',
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(obj)
            })
            .then(resp => resp.json())
            .then(res =>{
                if(res) alert('Added Successfully');
                else alert('Failed,Try Again');
            }).catch(err=> {console.log(err);alert(err)});
        }

The CORS is enabled in backend and working (checked by POSTMAN).

Success:- Success Caught Error :- without ACAO with ACAO

I run the fetch command in console and it worked fine but not in my React js App

Catch is logging error but still data is being posting

Error:- TypeError: Failed to fetch

3 Answers3

0

If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.

Sherin Shaju
  • 246
  • 4
  • 15
0

Add Allow CORS: Access-Control-Allow-Origin extension to your chrome or browser then enable it and check the reponse after that

0

I was using Form to take the input from user due to which before fetching, page was reloaded and it showed 'failed to Fetch' and status was shown "Cancelled" in Chrome developer tools. To fix this I used Div tag.