2016-05-04 30 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> 
) 
}