繁体   English   中英

使用React.js + Express.js发送电子邮件

[英]Send an Email Using React.js + Express.js

我在ES6中使用React.js构建了一个Web应用程序。 我目前想要创建一个基本的“联系我们”页面,并希望发送电子邮件。 我是React的新手,刚刚发现我实际上无法使用React本身发送电子邮件。 我正在使用nodemailerexpress-mailer跟踪教程,但是在将示例代码与我的React文件集成时遇到了一些困难。 具体来说,调用node expressFile.js有效,但我不知道如何将它链接到我的React前端。

Nodemailer: https//github.com/nodemailer/nodemailer

快递邮件: https//www.npmjs.com/package/express-mailer

我的表单的React组件如下。 我如何编写一个Express文件,以便从我的React组件中的contactUs()方法调用它? 谢谢!

import React from 'react';
import {
  Col,
  Input,
  Button,
Jumbotron
} from 'react-bootstrap';

class ContactView extends React.Component{
  contactUs() {
    // TODO: Send the email here

  }
  render(){
    return (
      <div>
    <Input type="email" ref="contact_email" placeholder="Your email address"/>
    <Input type="text" ref="contact_subject" placeholder="Subject"/>
    <Input type="textarea" ref="contact_content" placeholder="Content"/>
    <Button onClick={this.contactUs.bind(this)} bsStyle="primary" bsSize="large">Submit</Button>
  </div>
)
  }
};

export default ContactView;

单击该按钮时,对您的快速服务器执行ajax POST请求,即“/ contactus”。 / contactus可以从帖子数据中提取电子邮件,主题和内容,并发送到邮件功能。

在React中:

$.ajax({
    url: '/contactus',
    dataType: 'json',
    cache: false,
    success: function(data) {
        // Success..
    }.bind(this),
    error: function(xhr, status, err) {
        console.error(status, err.toString());
    }.bind(this)
});

在Express中,在明确的邮件处理程序中添加nodemailer代码:

app.post('/contactus', function (req, res) {
    // node mailer code
});

@ ryan-jenkin是完全正确的。

或者,如果您没有/希望jQuery作为依赖项,则可以使用本机fetch api 此外,我通常设置我的表单,以便每个输入都有一个状态,然后在字符串化的blob中使用该状态。

客户端(React):

handleSubmit(e){
  e.preventDefault()

  fetch('/contactus', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.state.email,
      // then continue this with the other inputs, such as email body, etc.
    })
  })
  .then((response) => response.json())
  .then((responseJson) => {
    if (responseJson.success) {
      this.setState({formSent: true})
    }
    else this.setState({formSent: false})
  })
  .catch((error) => {
    console.error(error);
  });
}

render(){
  return (
    <form onSubmit={this.handleSubmit} >
      <input type="text" name="email" value={this.state.email} />
      // continue this with other inputs, like name etc
    </form>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM