0

I am getting a similar error from (here)[Getting "TypeError: failed to fetch" when the request hasn't actually failed

My method is annotated with @CrossOrigin

With postman my request works fine ( from locally)

see POST to http://star-is.info:8080/app-1.0.0-BUILD-SNAPSHOT/register with headers Content-Type application/x-www-form-urlencoded and passing a string with firstname

Locally works fine but my form (here)[http://star-is.info:8082/] does not

       const data = {};
        data['firstname'] = this.state.firstname;
        console.log('submitSignup');
        fetch('http://localhost:8080/app-1.0.0-BUILD-SNAPSHOT/register', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then((response) => response.json()
        .catch(err => {
            console.err(`'${err}' happened!`);
            return {};
        })).then(function (body) {
            console.log(body);
        })
        .catch(error => {
     alert(error);
  });


Now I am getting a reply from server

{firstname: null}

but why is firstname not being passed to the server..

The way i achieved this much as using register as endpoint to call in fetch and using proxy in package.json


I removed JSON.stringify with the data and still it is null

See with postman I get the same string back

String sent is returned


I even tried this

const data = {'firstname' : this.state.firstname};

it is still returned null

2
  • @S.Iqbal please share the error as well. May 2, 2018 at 18:36
  • Type error failed to fetch..... line1 of my post
    – Eshan I.
    May 2, 2018 at 18:51

1 Answer 1

0

Finally it works. I had to encode the data being sent. Is there a better way to do this in Reactjs for more complex objects

const searchParams = Object.keys(data).map((key) => { return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]); }).join('&');

And then use searchParams in the body of fetch

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.