我有一个带有 Node.js 后端的 React 网站,该网站通过我的 GitHub 帐户部署到 Heroku。 React 网站前端将联系表单请求发送回 Node.js 后端服务器,后者通过 SMTP 将它们发送到收件箱。然而,虽然代码在本地主机上完美运行,但我在 Heroku 部署方面遇到了一些问题。我能够通过代码更新、升级我的测功机等来修复许多问题,但最后一个令人困惑,因为我认为代码正在工作,但 Node.js 服务器在某种程度上优先于 React 前端,导致没有要显示的实际前端组件。当我注释掉 Procfile 中的配置时(
web: node server.js
),前端代码可以工作,但代价是没有后端。我不知道从这里该去哪里。
这是我的node.js后端代码(server.js):
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const cors = require('cors');
const creds = require('./config');
const transporter = nodemailer.createTransport({
host: "smtp.mailtrap.io", // Use the correct Mailtrap SMTP server
port: 2525,
auth: {
user: creds.USER,
pass: creds.PASS
}
});
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/send', (req, res) => {
const { name, email, message } = req.body;
const content = `name: ${name} \n email: ${email} \n message: ${message}`;
const mail = {
from: email, // Set 'from' as a valid email address
to: '<VALID EMAIL HERE IN MY CODE>', // Change to the email address that you want to receive messages on
subject: 'New Message from Contact Form',
text: content
};
transporter.sendMail(mail, (err, data) => {
if (err) {
console.log(err); // Log the error for debugging
res.status(500).json({
status: 'fail',
error: err.message
});
} else {
res.status(200).json({
status: 'success'
});
}
});
});
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', router);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
这是我的前端 Contact.js 代码:
import React from 'react';
import "../App.css";
import "./Contact.css";
import FormData from 'form-data';
function Contact() {
function handleSubmit(event) {
event.preventDefault();
const form = event.target;
const formInfo = new FormData(form);
const jsonBody = Object.fromEntries(formInfo.entries()); // Ensure correct conversion
console.log(jsonBody);
async function fetchData() {
try {
// Determine the base URL dynamically based on environment
const baseURL = `${window.location.protocol}//${window.location.hostname}:3002`;
const response = await fetch(`${baseURL}/send`, {
method: "POST",
body: JSON.stringify(jsonBody),
headers: {
"Content-Type": "application/json"
}
});
const result = await response.json();
if (result.status === "success") {
alert("Message sent!");
} else {
alert("Message failed to send.");
}
} catch (error) {
console.error('Error:', error);
alert("Message failed to send due to an error.");
}
}
fetchData();
}
return (
<>
<div className="container">
<style>{'body { background-color: black; }'}</style>
<form method="post" onSubmit={handleSubmit}>
<label>Name: <input type="text" className = "textbox" name="name"></input></label>
<label>Email: <input type="email" className = "textbox" name="email"></input></label>
<div className="input-help">
<label> Message:
<textarea type="text" className = "textbox" name="message" placeholder="Thank you for messaging!" columns="200" rows="10" />
</label>
</div>
<button className = "submit-button" type="submit">Submit</button>
</form>
</div>
</>
);
}
export default Contact;
这是在终端中运行 Node server.js 时显示的服务器消息: 服务器在端口 3002 上运行 服务器已准备好接收消息 这是 localhost:3000:
上的可视代码从本地主机单击“提交”后,消息将发送到我的测试收件箱。 我知道这与 server.js 中的 app.get 和 res.send 代码有关,但如果没有它,整个代码根本无法在 Heroku 上运行。
这是部署到 Heroku 的应用程序,没有注释掉 Procfile:
否则,它看起来与 localhost 相同,但不发送电子邮件(尽管它确实在控制台中注册了 JSON 对象)。
以下是 Web 进程的 Heroku 日志:
2024-05-22T16:30:51.008189+00:00 heroku[web.1]: Starting process with command `node server.js`
2024-05-22T16:30:52.247939+00:00 app[web.1]: Server running on port 16613
2024-05-22T16:30:52.353130+00:00 app[web.1]: Server is ready to take messages
2024-05-22T16:30:52.773075+00:00 heroku[web.1]: State changed from starting to up
以下是整个网站的 Heroku 日志:
2024-05-22T16:30:51.008189+00:00 heroku[web.1]: Starting process with command `node server.js`
2024-05-22T16:30:52.247939+00:00 app[web.1]: Server running on port 16613
2024-05-22T16:30:52.353130+00:00 app[web.1]: Server is ready to take messages
2024-05-22T16:30:52.773075+00:00 heroku[web.1]: State changed from starting to up
2024-05-22T16:33:47.166236+00:00 heroku[router]: at=info method=GET path="/" host=<website_name>.herokuapp.com request_id=<here> fwd="<numbers>" dyno=web.1 connect=0ms service=6ms status=200 bytes=244 protocol=https
2024-05-22T16:33:47.313441+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=<website_name>.herokuapp.com request_id=<here> fwd="<here>" dyno=web.1 connect=0ms service=4ms status=404 bytes=426 protocol=https
2024-05-22T16:48:06.188583+00:00 heroku[router]: at=info method=GET path="/" host=<website_name>.herokuapp.com request_id=<texthere> fwd="<numbers>" dyno=web.1 connect=0ms service=1ms status=304 bytes=181 protocol=https
Heroku 服务器位于负载均衡器后面,它们充当代理 试试
app.set("trust proxy", 1);