【问题标题】:Access express post method from with react component使用 react 组件访问 express post 方法
【发布时间】:2018-01-14 09:46:27
【问题描述】:

基本上,我正在创建一个电子邮件表单,其中包含服务器的视图和表达方式。它工作正常。

我只想在联系页面上重新呈现表单组件,而不是成功重定向。

无论如何我可以从反应组件中访问发布请求成功值吗?也许调用在“/contact”端点获取的联系人组件中的 fetch 方法?这会触发我 express.js 文件中的 app.post() 方法吗??

这是我在 react 中提交按钮的帖子请求:

handleFormSubmit = (name, email, text) => {

  axios.post('/contact', {
   name: name,
   email: email,
   text: text
  }).then(res => {
   this.setState({sent: true})
   console.log(this.state);
  }).catch(err => {
   console.log(err);
  })
}

这是我的快速 js 帖子:

server.post('/contact', async (req, res) => {
  try {
    sendMail(req.body).then(info => console.log(info))

    // I am getting a response here just fine
    console.log(res)

  } catch (error) {
    console.log('express line 25: ', error);
  }

});

我将 Next.js 和 nodemailer 与 GMail 一起使用

谢谢

【问题讨论】:

  • 快递服务器是否在运行?前端到后端/contacts的请求是否成功(通过)?能否请您至少上传服务器代码和组件?
  • 但是服务器在运行吗?请求是否到达服务器?
  • 服务器运行良好,我收到来自服务器的响应,该服务器在发送帖子并获得响应后登录到终端。电子邮件在邮箱中到达很好,只是没有得到对前面的响应,甚至 axios.post 方法
  • 酷。您能否使用发起请求的前端代码更新您的问题?

标签: javascript node.js reactjs express


【解决方案1】:

好吧,对不起,问题与任何代码无关,它的下一个 js 设置,我构建并运行,似乎返回正常!

【讨论】:

    【解决方案2】:

    我没有看到您的代码,但如果我们在 React 组件中使用 fetch,请尝试使用 componentDidMount

    class Contact extends React.Component {
      constructor(props) {
          super(props);
          this.state = {data: null, isLoading: true}; 
      }
    
      // from the server 
      componentDidMount() {
          fetch('/contact').then( response =>  response.json()
          ).then( data => {
              this.setState({data, isLoading: false}); // es6 syntax same as this.setState({data: data, isLoading: false})
          }).catch( err => {
              throw new Error(err);
          });
      }
    
      render() {
         const {data, isLoading} = this.state;  
         if(isLoading){return (<div>Loading...</div>)} //no data fetched in  the initial render 
          return (
              <div>
                {data}
              </div> 
         );
      }
    }
    

    希望对您有所帮助。

    【讨论】:

    • 我有同样的设置,但使用 axios 而不是 fetch,我想在表单提交时进行,所以在提交按钮时运行一个函数,即使正在发送电子邮件也没有得到回复.在 componentDidMount 中发送它有什么好处?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2019-02-27
    相关资源
    最近更新 更多