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

4
  • stackoverflow.com/questions/49343024/… Commented Dec 3, 2020 at 5:48
  • I tried it but failed. I added ACAO in fetch and tried again but not resolved. I have attached error pic with response header with and without ACAO Commented Dec 3, 2020 at 6:06
  • Does your backend display any errors? Commented Dec 4, 2020 at 8:29
  • No, The data is successfully post in DB. Fro backend I am sending response true if success and false if err Commented Dec 5, 2020 at 13:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had tried both, with ACAO and without it too. I attached error pic of both showing response header.
0

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

1 Comment

I enabled and tested. It passed but issue is still there
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.