【发布时间】:2020-01-03 19:46:33
【问题描述】:
我在使用 React 与前端的 axios 和 Express 与 localhost 的后端的 nodemailer 联系表单时遇到问题。预期的结果是,当我单击“提交”按钮时,我应该会收到电子邮件,但是当我单击它时,网站会刷新,并且 URL 会更改为:http://localhost:3000/?email=test%40gmail.com&message=fdsfd,如果我在 email 字段中传递 test@gmail.com,并且没有收到邮件。
我的前端包含 App.tsx 文件(我使用 reactstrap 进行样式设置):
import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input } from "reactstrap";
import axios from "axios";
class App extends Component {
state = {
email: "",
message: ""
};
handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ email: e.target.value, message: e.target.value });
};
async handleSubmit(e: React.ChangeEvent<HTMLInputElement>) {
e.preventDefault();
const email = {
email: this.state.email
};
const message = {
message: this.state.message
};
const form = await axios.post("/api/form", {
email,
message
});
}
render() {
return (
<>
<div>
<Form id="contact-form">
<FormGroup onSubmit={this.handleSubmit} method="POST">
<Label for="exampleEmail">Email</Label>
<Input
type="email"
name="email"
id="email"
placeholder="with a placeholder"
onChange={this.handleChange}
/>
</FormGroup>
<FormGroup>
<Label for="exampleMessage">Message</Label>
<Input
type="textarea"
name="message"
id="message"
placeholder="with a placeholder"
onChange={this.handleChange}
/>
</FormGroup>
<Button type="submit">Submit</Button>
</Form>
</div>
</>
);
}
}
export default App;
我的后端包含 index.ts 文件:
import express, { Application, Request, Response, NextFunction } from "express";
import bodyParser from "body-parser";
import nodemailer from "nodemailer";
const app: Application = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/api/form", (req: Request, res: Response) => {
nodemailer.createTestAccount((err, account) => {
const htmlEmail = `
<h3>Contact details</h3>
<ul>
<li>Email: ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "MY_TEST_EMAIL_NAME",
pass: "MY_TEST_EMAIL_PASSWORD"
}
});
const mailOptions = {
from: "test@testaccount.com",
to: "MY_TEST_EMAIL_NAME",
replyTo: "test@testaccount.com",
subject: "new message",
text: req.body.message,
html: htmlEmail
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
return console.log(err);
}
console.log("message sent: %s =", info.message);
console.log("message URL: %s =", nodemailer.getTestMessageUrl(info));
});
});
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
为了启动应用程序(后端和前端),我同时使用如下所示:
"scripts": {
"build": "tsc -p backend/.",
"backend": "nodemon backend/dist/index.js",
"frontend": "cd frontend && yarn start",
"dev": "concurrently --kill-others-on-fail \"yarn backend\" \"yarn frontend\""
},
应用启动后终端输出如下图:
yarn run v1.17.3
$ concurrently --kill-others-on-fail "yarn backend" "yarn frontend"
$ nodemon backend/dist/index.js
$ cd frontend && yarn start
[0] [nodemon] 1.19.1
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching: *.*
[0] [nodemon] starting `node backend/dist/index.js`
$ react-scripts start
[0] Server listening on port 5000
[1] Starting the development server...
[1]
[1] Compiled with warnings.
[1]
[1] ./src/App.tsx
[1] Line 25: 'form' is assigned a value but never used @typescript-eslint/no-unused-vars
[1]
[1] Search for the keywords to learn more about each warning.
[1] To ignore, add // eslint-disable-next-line to the line before.
点击“提交”后可以更改什么来接收电子邮件?似乎从未使用过使用 axios 定义的表单,但我不知道如何修复它。这是我在 StackOverflow 上的第一篇文章。提前致谢。
【问题讨论】:
-
查看您的路由处理程序,您通常不应该做的一件事是在路由处理程序内部实例化传输器对象。从
createTransport方法创建的传输器对象至少应该定义在模块的顶部,在路由处理程序之外,如果不是在单独的模块中处理对其的直接访问,以便在您的服务器中抽象使用。这可能是这里问题的一部分
标签: reactjs typescript express axios nodemailer