所以我有一个只有两个文本字段和一个按钮的表单 . 当用户点击要提交的按钮时,我有一个handleSubmit函数,它在后端的express文件中执行axios post . 这一切都有效,除了重定向,i console.log显示文件中app.post中的数据,它正确显示数据,并且它也显示在数据库中 .
这就是表单的样子
<form onSubmit={this.handleSubmit} className="col s12 row">
<div className="row">
<div className="input-field col s6">
<input
value={this.state.title}
type="text"
className="validate"
onChange={this.handleTitleChange} />
<label className="active">Title</label>
</div>
</div>
<div className="row">
<div className="input-field col s6">
<textarea
id="textarea1"
value={this.state.body}
className="materialize-textarea"
onChange={this.handleBodyChange} />
<label className="active">Title</label>
</div>
</div>
<div className="row">
<div className="input-field col s6">
<button className="btn waves-effect waves-light" type="submit" name="action">Submit
<i className="material-icons right">send</i>
</button>
</div>
</div>
</form>
这是handleSubmit方法
handleSubmit(event) {
axios.post('/api/newBlog', this.state)
.then(res => console.log(res));
}
最后是路由器代码
app.post('/api/newBlog', (req, res) => {
console.log(req.body);
const blogPost = new Blog(req.body);
blogPost.save();
res.redirect("/")
});
每当我按下提交按钮时,它会将我重定向到同一页面,但略有不同 . 新博客表单的页面是我的react-router中定义的“http://localhost:3000/newblog ", but after clicking submit, it redirects me to " http://localhost:3000/newblog?action= " . Why is "?action = " showing up in the url, and why is it not redirecting to " / "? I have " /”,如果我在网址中手动输入,我可以到达那里 .
1 回答
==>因为默认情况下提交方法是Get not Post . (如果你没有在表单标签中设置method ='POST') .
当点击提交按钮时,将提交标签的所有值都具有属性名称 . 追加到Url中(如果method = get)
在你的情况下
<button name='action' ...
网址将youdomain?action=
并且您没有设置操作,这意味着默认提交到当前URL
如果你想手动重定向,你可以使用:
event.preventDefault()
inhandleSubmit()
方法,如下所示:或者将click事件添加到按钮中并删除type ='submit'
希望,它可以帮助你