2016-05-04 29 views
2

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

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

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

我的阵营组成部分的形式如下。我如何编写一个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; 

回答

7

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

在阵营:

$.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) 
}); 

在快递明确后处理程序中添加代码nodemailer:

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

提供了一个更详细的回答了代码示例将有助于OP –

+0

谢谢你的建议,这听起来像它会工作!这也可能是一个愚蠢的问题,但现在,当我编译我的应用程序时,我只是运行''npm start'''。我将如何让我的快递服务器同时运行? –

+0

您使用node:node expressFile.js启动express服务器 –

3

@瑞安詹金是完全正确的。或者,如果您没有/希望将jQuery作为依赖项,则可以使用本机fetch api。另外,我通常设置我的表单,以便每个输入都有一个状态,然后在字符串化的对象中使用该状态。

客户端(反应):

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> 
) 
}