REACT提取帖子请求

REACT提取帖子请求

本文介绍了REACT提取帖子请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对路由发布请求有疑问我需要建立注册表单并将表单的输入内容发布到mongodb我在服务器端制作了路由器并发布了路由,并且工作正常(当我使用邮递员时)

I have problem with routing post requestI need to build register form and post input from form to mongodbI made router and post route on server side and it works ok (when I use postman)

//表格为必填模型

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

但是我需要从客户端而不是邮递员处将其解雇.在这里我迷路了.我可以做到,但是当我添加onSubmit操作时,它不起作用.而且我需要使用新功能来触发另一件事,而无需重定向到另一页面.如何将this.refs.first_name.value传递给正文,以便我可以使用提取函数?在反应成分下方

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

添加了此JavaScript/JSON代码段

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

推荐答案

我认为您不赞成使用ref的方式.尝试下面的方法,看看您是否有运气.

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

这是一个链接,用于对有关refs

Here is a link to react docs about refs

这篇关于REACT提取帖子请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:43