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

Eshan I.
  • 75
  • 1
  • 10

1 Answers1

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

Eshan I.
  • 75
  • 1
  • 10