我有一个表单,我想通过
STMP
使用 nodemailer
中的 express
将数据发送给电子邮件订阅者。我无权使用数据库,并且收到错误消息 body-parser middleware
。
我从客户那里收到的错误:
Request failed with status code 404
,ERR_BAD_REQUEST
。
我从服务器收到的错误:
ReferenceError: firstnameprop is not defined
尝试启动服务器时 `
我唯一可以发送我在
nodemailer
中编写的测试电子邮件的时间是服务器重新启动时。我的目标是仅在发送请求时从表单发送数据,而不是通过重新启动服务器。
过去使用数据库、控制器和路由,我成功地集成了客户端和服务器端进行通信。没有数据库,我无法声明该道具。
我的问题是
body-parser
出了什么问题? (是的,它已安装)我还能如何排除故障?我错过了什么吗?
更新:我向
Axios req
添加了标头,并更新了 `server.js
第二次更新:让客户端工作,我将
app.get
更改为app.post
,服务器仍然返回未定义
index.js
const express = require("express");
//应用程序
const app = express();
const bodyParser = require("body-parser");
const jsonParser = bodyParser.json();
const cors = require("cors");
const morgan = require("morgan");
const nodemailer = require("nodemailer");
// morgan
app.use(morgan("tiny"));
app.use(jsonParser); // use it globally
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
// server routee
app.get("/", (req, res) => {
res.json({ message: "Hello world" });
});
// send route route
app.post("/send-email", jsonParser, (req, res) => {
const { firstnameprop } = req.body;
console.log("response", res);
});
let transporter = nodemailer.createTransport({
host: "smtp.office365.com",
port: 465,
secure: false,
auth: {
user: "...",
pass: "...",
},
});
let mailOptions = {
from: "someemail.com",
to: "someemail.com",
subject: "Sending Email using Node.js",
text: `Name: ${firstnameprop}`,
//ERROR IS BELOW, PROP IS NOT DELARED, HOW CAN I FIX THIS?
html: `<html><body><h1>Hello ${firstnameprop} !</h1><p>This is a test from development server from website.com/</p></body></html>`,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
app.listen(5000, () => {
console.log("Server started on port 5000");
});
HireingForm.js
import { useNavigate } from "react-router-dom";
import { Card, Col, Form, Row } from "react-bootstrap";
import { useRef, useState } from "react";
import axios from "axios";
//some more imports
const HiringForm = () => {
const matchSm = useMediaQuery("(max-width: 728px)");
const refForm = useRef();
// props
const [firstnameprop, setFirstNameProp] = useState("");
const sendEmailHandler = (e) => {
e.preventDefault();
console.log("submitted list", firstnameprop);
axios
.post(
"http:.localhost:5000/send-email",
{ firstnameprop },
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
{/* NOTE, THE FORM WORKS, I CONSOLED THE PROP AND WAS SUCCESSFUL WITH THE LOG */}
return (
<>
<Form
ref={refForm}
onSubmit={sendEmailHandler}
className={hiring}
autoComplete="on"
>
<FirstName
firstnameprop={firstnameprop}
setFirstNameProp={setFirstNameProp}
/>
{!checked ? <SubmitButton /> : <SubmitButtonDisabled />}
</Form>
</>
export default HiringForm;
得到答案:
问题出在我有
/send-email endpoint
的两个客户端上,我将其更改为http://localhost5000.send-email
我还添加了一个标题”
axios
.post(
"http://localhost:5000/send-email",
{ firstnameprop },
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
服务器的解决方案,经过研究和发现这个问题:我实现了代码并做了一些额外的更改,我将其粘贴在下面:
如您所见,我将
app.post
更改为 try and catch
,包括一些 plain HTML
,并且 smtpTransport.sendMail function
请注意,smtpTransport = nodemailer.createTransport function
超出了 try catch function
。我通过了 firstnameprop
和 req.body.firstnameprop
和 not const {firstnameprop} = req.body
我发现在这种情况下不使用 HTML
模板是最好的。
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const jsonParser = bodyParser.json();
const cors = require("cors");
const morgan = require("morgan");
// morgan
app.use(morgan("tiny"));
const nodemailer = require("nodemailer");
let smtpTransport = require("nodemailer-smtp-transport");
app.use(jsonParser); // use it globally
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(cors());
//server route
app.get("/", (req, res) => {
res.json({ message: "Hello world" });
});
//CHANGES START HERE --------------------------------------
app.post("/send-email", (req, res) => {
console.log(req.body);
try {
const mailOptions = {
from: "[email protected]",
to: "[email protected]",
subject: "Sending Email Test",
html: `
<p>You have a new contact request.</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.firstnameprop}</li>
</ul>
`,
};
smtpTransport.sendMail(mailOptions, (err, info) => {
if (err) {
res.status(500).send({
success: false,
message: "Something went wrong. Try again later",
});
} else {
res.send({
success: true,
message: "Thanks for contacting us. We will get back to you shortly",
});
}
});
} catch (error) {
res.status(500).send({
success: false,
message: "Something went wrong. Try again later",
});
}
});
smtpTransport = nodemailer.createTransport(
smtpTransport({
host: "...",
port: 465,
secure: true,
auth: {
user: "...",
pass: "...",
},
})
);
app.listen(5000, () => {
console.log("Server started on port 5000");
});