提交表单后,为什么页面不会重定向?

时间:2018-05-21 22:37:46

标签: javascript node.js reactjs express

所以我有一个只有两个文本字段和一个按钮的表单。当用户点击要提交的按钮时,我有一个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("/")
    });

每当我按下提交按钮时,它会将我重定向到同一页面,但略有不同。新博客表单的页面为“http://localhost:3000/newblog”,但在点击提交后,它会将我重定向到“http://localhost:3000/newblog?action=”。为什么“?action =”出现在网址中,为什么不重定向到“/”?我在我的react-router中定义了“/”,如果我在网址中手动输入它,我就可以到达那里。

1 个答案:

答案 0 :(得分:0)

  

&#34;为什么&#34;?action =&#34;显示在网址中,为什么不显示   重定向到&#34; /&#34;?我有&#34; /&#34;在我的react-router中定义,我可以   如果我在网址中手动输入它,请到那里。&#34;

==&GT;因为默认情况下提交方法是Get not Post。(如果你没有设置方法=&#39; POST&#39;在表格标签中)。

当点击提交按钮时,将提交标签的所有值都具有属性名称。在Url中附加(如果method = get)

在您的情况下<button name='action' ... 网址将为youdomain?action=

您还没有设置操作,这意味着默认提交到当前网址

如果您想要手动重定向,可以在event.preventDefault()方法中使用handleSubmit() 像这样:

handleSubmit(){
event.preventDefault();
// call API here, redirect url...

}

或者在按钮中添加点击事件,然后移除type =&#39;提交&#39;

<button onClick={this.handleSubmit.bind(this)}>Submit</button>

希望,它可以帮到你

相关问题