1
votes
handleSubmit = e => {
e.preventDefault();
var data = new FormData();
data.append( "name", this.state.first_name + ' ' +this.state.last_name);
data.append( "password", this.state.password);
data.append( "email", this.state.email);
data.append( "phone_no", this.state.phone_no);
console.log(data)
fetch("http://localhost:8080/register",{
  method: "POST",
  body: data,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }

}) .then(res => res.json()) .then( (result) => { if(result.status == 'failure'){ alert(result.data) console.log(result) }else { this.setState({ isLoaded: true, }); } // this.props.history.push('/dashboard'); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) }

the expected data should be something like

{ name: 'mayank', email: '[email protected]', password: 'password' }

what it is returning is

{ '------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name': '"name"\r\n\r\   nMayank nauriyal\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name   ="password"\r\n\r\npassword\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form   -data; name="email"\r\n\r\[email protected]\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Dispo   sition: form-data; name="phone_no"\r\n\r\n\r\n------WebKitFormBoundarynYkonogmAGuTwWsy--\r\n' }
1
Why don't you send JSON instead of form? - Bruno Paulino
It is sending the right data, in wrong format. Change application/x-www-form-urlencoded to application/json, and change the body to JSON.stringify(object) instead of FormData. - Amadan
Thanks buddy, I was stuck at this silly thing for 1 hr. - Mayank Nauriyal

1 Answers

3
votes

Send JSON instead of FormData:

var jsObject = {name: 'John', password: 'foo', email: '[email protected]'};

fetch(url, {
  method: 'POST',
  body: JSON.stringify(jsObject),
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));