【发布时间】:2021-04-17 02:37:28
【问题描述】:
我用这个https://medium.com/weekly-webtips/create-and-deploy-your-first-react-web-app-with-a-node-js-backend-ec622e0328d7 创建了 React 前端和 NodeJS 后端。在本地运行时,它可以工作,但我将它部署在 Heroku 上。我没有收到来自 express server api 的任何响应。
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
我的代理设置如下所示
结果为 http://localhost:3000/
来自前端的您好! 你好测试!!!
结果为@987654322@ 来自前端的您好!
“代理”:“http://localhost:5000”,
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
// Create a new express application named 'app'
const app = express();
// Set our backend port to be either an environment variable or port 5000
const port = process.env.PORT || 5000;
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
};
// // Catch any bad requests
// app.get('*', (req, res) => {
// res.status(200).json({
// msg: 'Catch All'
// });
// });
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
// Configure our server to listen on the port defiend by our port variable
app.listen(port, () => console.log(`BACK_END_SERVICE_PORT: ${port}`));
任何帮助都会很棒
【问题讨论】:
-
你可以添加整个 API 文件或者你正在初始化服务器的地方,并确保你已经像这样初始化了服务器端口,让 PORT = process.env.PORT || 5000;
-
@akshay 添加了 server.js 文件
标签: node.js reactjs heroku deployment