Javascript 响应获取post请求

Javascript 响应获取post请求,javascript,mongodb,rest,reactjs,fetch,Javascript,Mongodb,Rest,Reactjs,Fetch,我在发送post请求时遇到问题 我需要构建注册表单并将表单中的输入发布到mongodb 我在服务器端制作了路由器和post路由,它工作正常(当我使用postman时) //表格是模型所必需的​ router.route('/').post(函数(req、res、next){ res.send(请求正文) 创建( {“first_name”:req.body.first_name, “姓氏”:req.body.last_名称 }) .then(函数(数据){ res.send(数据); 控制台日志

我在发送post请求时遇到问题 我需要构建注册表单并将表单中的输入发布到mongodb 我在服务器端制作了路由器和post路由,它工作正常(当我使用postman时)

//表格是模型所必需的​
router.route('/').post(函数(req、res、next){
res.send(请求正文)
创建(
{“first_name”:req.body.first_name,
“姓氏”:req.body.last_名称
})
.then(函数(数据){
res.send(数据);
控制台日志(数据);
}).catch(函数(err){console.log(err)});

});我猜您使用
ref
的方式已经被弃用了。试试下面,看看你有没有运气

导出默认类表单扩展React.Component{
建造师(道具){
超级(道具);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(事件){
event.preventDefault();
获取(“/”{
方法:“post”,
标题:{'Content-Type':'application/json'},
正文:{
“first_name”:this.firstName.value
}
});
};
渲染(){
返回(
{this.firstName=ref}}占位符=“First Name”type=“text”Name=“First\u Name”/>
{this.lastName=ref}}占位符=“Last Name”type=“text”Name=“Last\u Name”/>
开始 ​ ​ ) }
}
您可以使用受控组件的概念

为此,添加状态值

constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
  this.state={ firstname:"", lastname:""} 
}
现在输入如下字段:

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

我们需要将发送数据作为json字符串化

handleSubmit(event){ 
    event.preventDefault();
    fetch('/', {
       method: 'post',
       headers: {'Content-Type':'application/json'},
       body: JSON.stringify({
            "first_name": this.state.firstName
       })
    });
};

这就是我在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);
   });

也许您使用绑定引用的方法是正确的。但这还不是解决方案。我在服务器控制台中只得到一个错误:“错误:发送后无法设置标题。在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:357:11)…我在db中看到值为0的新文档。请尝试
标题:{'Content-Type':'application/json'},
在fetch中查看该帮助是否存在,同样,在您将请求发送到
/form
而不是
/
时,也可以尝试使用
body:JSON.stringify({“first\u name”:this.firstName.value})
body:JSON.stringify()
对我有效。
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);
   });