[英]Send an Email Using React.js + Express.js
我在ES6中使用React.js構建了一個Web應用程序。 我目前想要創建一個基本的“聯系我們”頁面,並希望發送電子郵件。 我是React的新手,剛剛發現我實際上無法使用React本身發送電子郵件。 我正在使用nodemailer
和express-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.