React Fetch Post Request
I have problem with routing post request I need to build register form and post input from form to mongodb I made router and post route on server side and it works ok (when I use p
Solution 1:
I guess the way you are using ref
has been deprecated. try below see if you have any luck.
exportdefaultclassFormextendsReact.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 (
<divid="signup"><formonSubmit={this.handleSubmit}><inputref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/><br /><inputref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/><br /><buttontype="Submit">Start</button></form>
</div>
)
}
}
Here is a link to react docs about refs
Solution 2:
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
})
});
};
Solution 3:
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);
});
Solution 4:
You can use the concept of controlled components.
For that, add state value,
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.state={ firstname:"", lastname:""}
}
Now input fields to be like,
<input placeholder="First Name" type="text" value={this.state.firstname} onChange={(ev)=>this.setState({firstname:ev.target.value})}/>
<input placeholder="Last Name" type="text" value={this.state.lastname} onChange={(ev)=>this.setState({lastname:ev.target.value})}/>
and handleSubmit should be like,
handleSubmit(event){
event.preventDefault();
fetch('/', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: {
"first_name": this.state.firstName
}
});
};
Post a Comment for "React Fetch Post Request"