将发布请求发送到后端API时关闭表单而不重新加载页面

时间:2019-02-20 09:25:35

标签: javascript node.js reactjs api express

这可能很简单,但是我有一个React前端和Express后端,我正在通过前端的表单将数据发送到我的API。我有两个按钮,一个提交和一个关闭。 “关闭”按钮具有单击事件处理程序,该事件处理程序可在不离开页面的情况下关闭叠加层。我希望我的“提交”按钮使用onSubmit处理程序可以正常工作。但是,即使我的发布请求成功完成,即使使用相同的功能,它也不会关闭叠加层。

我可以通过在后端使用res.redirect来使应用程序正常工作,但是理想情况下,我希望页面不会重新加载。另外,当我让后端使用res.send()或res.json()向后发送任何类型的数据时,它会在浏览器中加载JSON数据,而不是在前端进行处理(例如,显示我的所有帖子Posts.js组件)。

相关代码:

发布路线

router.post('/', (req, res) => {

  Post.create(req.body)
    .then(newPost => {
        console.log("Success!")
        res.status(201).json(newPost);
        //res.redirect('http://localhost:3000');
    })
    .catch(err => {
      console.log(err);
      res.send(err);
    })
})

形成并关闭覆盖功能

handleClose(e) {
    this.props.closeForm();
    e.preventDefault();
  }

  render() {
    const postForm =
    <div className="form-popup" id="newPost">
      <form action="http://localhost:5000/api/posts" method="post" className="form-container">

        <h1>New Blog Post</h1>
        <div className="formArea formtitle">
          <label htmlFor="title"><b>Title</b></label>
          <input type="text" placeholder="Blog Post Title" name="title" required />

        </div>
        <div className="formArea formlocation">
          <label htmlFor="location"><b>Location</b></label>
          <input type="text" placeholder="Location" name="location" required />
        </div>
        <div className="formArea postcontent">
          <textarea placeholder="Your post here" name="bodyText" required />
        </div>
        <div className="formArea formsubmit">
          <button type="submit" className="btn" onSubmit={this.handleClose} >Post</button>
          <button type="submit" className="btn cancel" onClick={this.handleClose}>Close</button>
        </div>

      </form>
    </div>

2 个答案:

答案 0 :(得分:0)

两个选项

  • 推荐:使用 Ajax通话
  • 通过JavaScript发送请求
  • 棘手的解决方案:在页面中插入iframe tag,并将form设为目标

XHR

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");

iframe

<iframe name="formTarget" style="display:none;"></iframe>
<form action="http://localhost:5000/api/posts" method="post" target="formTarget">
    <!--Your inputs and other form contents-->        
</form>

答案 1 :(得分:0)

您的问题与Node.js无关。阅读有关controlled componentsaxios的信息。

要执行此操作,请将您的代码更改为以下内容:

    import React from 'react';
    import axios from 'axios';

    class YourComponent extends React.Component {

        constructor(props) {
            super(props);
            this.state = {
                title: '',
                location: '',
                bodyText: ''
            };

            handleOnInputChange = (event)=> {
                const target = event.target;
                const value = target.type === 'checkbox' ? target.checked : target.value;
                const name = target.name;

                this.setState({
                  [name]: value
                });
            }

            handleSubmitForm = ()=> {
                const { title, location, bodyText } = this.state;

                axios.post('http://localhost:5000/api/posts', {
                    userName: name,
                    userLocation: location,
                    text: bodyText
                })
                .then(response=> {
                    //Do something with the response
                    console.log(response)
                })
                .catch(error=>{
                    //Do something with the error
                    console.log(error)
                })
            }
        }

        render(){
            <div className="form-popup" id="newPost">
             <form className="form-container">

               <h1>New Blog Post</h1>
               <div className="formArea formtitle">
                 <label htmlFor="title"><b>Title</b></label>
                 <input type="text" placeholder="Blog Post Title" name="title" required value={this.state.title} onChange={event => this.handleOnInputChange(event)} />

               </div>
               <div className="formArea formlocation">
                 <label htmlFor="location"><b>Location</b></label>
                 <input type="text" placeholder="Location" name="location" required value={this.state.location} onChange={event => this.handleOnInputChange(event} />
               </div>
               <div className="formArea postcontent">
                 <textarea placeholder="Your post here" name="bodyText" required onChange={event => this.handleOnInputChange(event}>{this.state.bodyText}</textarea>
               </div>
               <div className="formArea formsubmit">
                 <button type="button" className="btn" onSubmit={this.handleSubmitForm} >Post</button>
                 <button type="button" className="btn cancel" onClick={this.handleClose}>Close</button>
               </div>

             </form>
           </div>
        }
    }
    export default YourComponent