26

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 postman)

//form is required model​

router.route('/').post(function(req,res,next){
 res.send(req.body)
 form.create(
  {"first_name": req.body.first_name,
  "last_name": req.body.last_name
 })
  .then(function(data){ 
  res.send(data);
  console.log(data);
 }).catch(function(err){console.log(err)});
});

But I need to fire it form client side, not postman. And here i am lost. I can do it with but when i add onSubmit action it doesnt work. And I need to use new function to fire another thing without redirecting to another page. How to pass this.refs.first_name.value to body so that i could use fetch function?? Below react component

added this JavaScript/JSON snippet

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }
 handleSubmit(event){ 
  event.preventDefault();
  console.log(this.refs.first_name.value);
  fetch('/', {
   method: 'post',
   body: {
    "first_name": this.refs.first_name.value
   }
  });
 };
 render () {
  return (
   
   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref="first_name" placeholder="First Name" type="text" name="first_name"/><br />
        <input placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>
​
   </div>
​
  )
 }
}

4 Answers 4

22

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
       })
    });
};
Sign up to request clarification or add additional context in comments.

Comments

20

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

7 Comments

Perhaps you are right with way to bind refs. But it's not solution yet. I get only error in server console: "Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)..." I in db I see new document with value=0.
Try headers: {'Content-Type':'application/json'}, in fetch see if that helps
Nope, still the same
here you are sending the request to /form not / and also try using body: JSON.stringify({ "first_name": this.firstName.value })
body: JSON.stringify(<insert your data here>) worked for me.
|
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);
   });

Comments

1

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
   }
  });
 };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.