REACT fetch post request
This is how I made my post request in React.js;
const res = fetch('http://15.11.55.3:8040/Device/Movies', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: {
id: 0,
},
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
we need to make sending data as json stringify
handleSubmit(event){
event.preventDefault();
fetch('/', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"first_name": this.state.firstName
})
});
};
I guess the way you are using ref
has been deprecated. try below see if you have any luck.
export default class Form extends React.Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
event.preventDefault();
fetch('/', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: {
"first_name": this.firstName.value
}
});
};
render () {
return (
<div id="signup">
<form onSubmit={this.handleSubmit}>
<input ref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/><br />
<input ref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/><br />
<button type="Submit">Start</button>
</form>
</div>
)
}
}
Here is a link to react docs about refs