Skip to content

Instantly share code, notes, and snippets.

@everdimension
Last active May 2, 2019 10:35
Show Gist options
  • Save everdimension/c74953456fd8a533b252508d4738733e to your computer and use it in GitHub Desktop.
Save everdimension/c74953456fd8a533b252508d4738733e to your computer and use it in GitHub Desktop.
class MyForm extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="birthdate">Enter your birth date</label>
<input id="birthdate" name="birthdate" type="text" />
<button>Send data!</button>
</form>
);
}
}
@mledwards
Copy link

mledwards commented Mar 14, 2019

Just a heads up, node's body-parser package doesn't support FormData being sent from the front-end.

I needed to JSON.stringify the body and pass a JSON header, like:

fetch('/api/add-user', {
      method: 'post',
      body: JSON.stringify({
        name: data.get('name'),
        email: data.get('email'),
        country: data.get('country')
      }),
      headers:{
        'Content-Type': 'application/json'
      }
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment