【发布时间】:2021-08-16 00:27:36
【问题描述】:
每次我在本地启动我的应用程序时,我都需要运行:
- npm start(启动我的 React 应用)
- node server.js(启动我的 node.js 服务器)
如何托管这个网站?
我遇到的另一个问题:
- 我在 localhost:3000 上运行我的 React 应用程序
- 我的 node.js 服务器监听 localhost:3000
结果: 当我刷新我的应用程序时,有时它会显示“无法获取 /”,因为它正在尝试获取 node.js 服务器而不是 React 应用程序。
这是我的 server.js 文件供参考
const express = require('express');
const nodemailer = require('nodemailer');
require('dotenv').config()
const app = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: process.env.EMAIL,
pass: process.env.PASS,
},
});
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
app.post('/send', (req, res, next) => {
console.log(req.body)
var name = req.body.contactName
var email = req.body.contactEmail
var subject = req.body.contactSubject
var message = req.body.contactMessage
var mail = {
from: name,
to: email,
subject: subject,
text: message
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
});
任何有关正确方法的建议将不胜感激。谢谢!
更新
显然,'Cannot Get /' 是 node.js react 应用程序的常见问题,我需要在 server.js 中添加类似的内容:
app.route("/").get(function (req, res) {
res.redirect("/public/index.html");
});
任何人都可以帮助使用此方法将 get 请求重定向到我的 node.js 服务器到我的 react 应用程序的主页吗?
【问题讨论】:
-
您是否使用 create-react-app 来引导您的 react 应用程序?只是想弄清楚你是否在使用 webpack。
-
你的意思是你的 react 应用监听 3000 端口吗?不能在同一个端口上运行两个不同的应用程序
-
正如 smac89 所说,你不能在同一个端口上运行两个应用程序。响应你的 api 调用什么 url?
-
我的错,我改写了这个问题。我的 sever.js 正在监听 localhost:3000(React 应用程序正在运行的地方)。是的,我使用 create-react-app 来引导反应应用程序。问题是当我刷新应用程序时说“无法获取/”,如果我使用“npm start”运行反应应用程序,加载网页(localhost:3000)然后运行“node server.js”启动我的服务器,一切正常,直到我刷新网页。之后它说“无法获取/”
-
还想知道这在部署环境中是如何工作的。我是否托管我的反应应用程序然后单独运行我的 node.js 服务器?我来自 C#/.NET 背景,所以如果这些问题看起来像愚蠢的问题,我深表歉意,哈哈