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

fel*_*iao 8 javascript email node.js express reactjs

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

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

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

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

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;
Run Code Online (Sandbox Code Playgroud)

Rya*_*kin 12

单击该按钮时,对您的快速服务器执行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)
});
Run Code Online (Sandbox Code Playgroud)

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

app.post('/contactus', function (req, res) {
    // node mailer code
});
Run Code Online (Sandbox Code Playgroud)

  • 使用代码示例提供更详细的答案将有助于OP (2认同)

bla*_*ace 6

@ 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>
  )
}
Run Code Online (Sandbox Code Playgroud)