Kam*_*ski 6 javascript rest fetch mongodb reactjs
我有路由发布请求的问题我需要建立寄存器表单并从表单到mongodb的后输入我在服务器端制作了路由器和发布路由它工作正常(当我使用邮递员时)
//表单是必需的模型
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)});
});Run Code Online (Sandbox Code Playgroud)
但我需要从客户端解决它,而不是邮递员.在这里,我迷失了.我可以这样做但是当我添加onSubmit动作时它不起作用.而且我需要使用新函数来触发另一个东西而不重定向到另一个页面.如何将this.refs.first_name.value传递给body,以便我可以使用fetch函数?以下反应成分
添加了此JavaScript/JSON代码段
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>
?
)
}
}Run Code Online (Sandbox Code Playgroud)
我们需要将发送数据作为 json 字符串化
handleSubmit(event){
event.preventDefault();
fetch('/', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"first_name": this.state.firstName
})
});
};
Run Code Online (Sandbox Code Playgroud)
我猜您使用的方式ref已被弃用.试试下面看看你有没有运气.
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>
?
)
}
}Run Code Online (Sandbox Code Playgroud)
这是一个反应文档的链接refs
| 归档时间: |
|
| 查看次数: |
55431 次 |
| 最近记录: |