我已经构建了一个表单,我希望能够发送电子邮件,为此我尝试遵循此 YouTube 教程:https://www.youtube.com/watch?v=_3-By9QfFa0
但是,我遇到了一个问题,在尝试提交表单时,我的控制台网络浏览器中出现问题标题错误。我意识到这个问题可能与某处的其中一条路线有关,但我就是无法弄清楚(除非它是完全不同的东西)。
schoolForm.js
const handleSubmit = async(e) => {
e.preventDefault();
try { //I also tried using only: "/send_mail" here like I have in server.js but it didnt work
await axios.post("http://localhost:3000/send_mail", {
name
});
}
catch (error) {
console.log(error);
}
}
服务器.js
const express = require("express");
const app = express();
require("dotenv").config();
const bodyParser = require("body-parser");
const cors = require("cors");
const nodemailer = require("nodemailer");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.post("/send_mail", cors(), async (req, res) => {
let {text} = req.body;
const transport = nodemailer.createTransport({
host: "smtp-mail.outlook.com",
port: 587,
auth: {
user: "[email protected]",
pass: "password"
},
tls: {
rejectUnauthorized: false
}
});
await transport.sendMail({
from: "[email protected]",
to: "[email protected]",
subject: "subject",
html: `<p>${text}</p>`
})
});
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
编辑:我在浏览器中遇到的错误:
有谁可以帮我解决这个问题吗?非常感谢您的帮助!
您的服务器正在侦听端口 4000。 // 服务器.js
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
您应该使用下面的 URL 进行 Axios 呼叫。 // schoolForm.js
await axios.post("http://localhost:4000/send_mail", { // use port 4000 not 3000
name
});
您已将服务器设置为侦听端口 4000,但您的
axios
请求是端口 3000。
确保将请求发送到正确的端口:
await axios.post("http://localhost:4000/send_mail", {
name
});
另请注意
body-parser
已弃用,您应该使用 express
内置中间件。所以代替:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
你应该:
app.use(express.urlencoded({extended: true}));
app.use(express.json());
并且您可以删除
body-parser
依赖性。
您可以阅读此处,了解有关 Express 内置中间件及其可选属性的更多信息。
编辑:
它不起作用的原因是因为
body
是中间件本身创建的对象。因此 req.body
是 undefined
,因为 body
对象不存在
兄弟我也遇到了同样的问题,但不知道发生了什么。我还检查了 URL、路由器和控制器,但一切正常。我也放了cors。