将React + NodeJS + Express + MySQL应用程序部署到Heroku仅部署服务器而不是React

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将React + NodeJS + Express + MySQL应用程序部署到Heroku仅部署服务器而不是React相关的知识,希望对你有一定的参考价值。

作为标题国家,我们有一个React + NodeJS + Express + mysql,我们正尝试将其部署到Heroku网页上。我将其设置为在每次将某些内容推送到GitHub的master分支时自动部署。

我们遇到的问题是它正在为服务器部署路由并显示所有正确的信息,但是react应用程序根本没有显示。如何使服务器路由不显示,但反应前端显示呢?

随附的是Server.js的代码以及我正在运行的用于构建客户端的脚本。

const express = require('express')
const cors = require('cors')
const app = express()
const path = require('path');
const port = process.env.PORT || 8080;


const homeRoute = require("./routes/home");
const allReviews = require("./routes/getAllReviews");
const mostRecentReviews = require("./routes/mostRecentReview");
const postReview = require("./routes/postReview");
const editReview = require("./routes/editReview");
const updateReview = require("./routes/updateReview");
const deleteReview = require("./routes/deleteReview");
const filterReview = require("./routes/getFilterReview");
const recentReviews = require("./routes/mostRecentReview");

const locationAverageRating = require("./routes/locationAverageRating");
const allLocations = require('./routes/allLocations');

app.use(cors())

app.use('/', homeRoute);
app.use('/review', allReviews);
app.use('/locations', allLocations);
app.use('/review/recent', mostRecentReviews);
app.use('/review/post', postReview);

app.use('/review/edit', editReview);
app.use('/review/update', updateReview);
app.use('/review/delete', deleteReview);
app.use('/review/filter', filterReview);
app.use('/carrier/recent',recentReviews);

app.use('/carrier/edit', editReview);

app.use('/carrier/locations', locationAverageRating);

app.use(express.static('client/build'));
app.get('*', (req, res) =>{
    res.sendfile(path.resolve(__dirname + "./client/build/index.html"));
});

const port = process.env.PORT || 8080;
app.listen(port, () => {
    console.log(`Example app listening on port ${port}!`)
});

Heroku构建脚本:

  "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

在此先感谢您的帮助,如果您需要任何其他文件或有任何疑问,请随时联系!

答案

[使用app.use时,顺序很重要。因为所有服务器路由都在到达react build的路由之前声明,所以服务器路由将具有优先权。

考虑为服务器路由添加前缀,以使其与应由前端构建处理的请求区分开(/api是常见选择)。

另一种选择是为前端指定路由(可能是/app)。您可以将某些GET请求重定向到homeRoute中的此路由,这样,如果有人通过根URL访问您的网站,那么他们最终会出现在正确的位置(假设您没有想要的其他GET路由) homeRoute处理。

因此您可以将通配符GET路由更改为如下所示:

app.get('/app*', (req, res) => {
  res.sendfile(path.resolve(__dirname + "./client/build/index.html"));
})

然后在“ homeRoutes”内部

app.get('*', (req, res) => {
  res.redirect('/app')
})
...other homeRoutes

以上是关于将React + NodeJS + Express + MySQL应用程序部署到Heroku仅部署服务器而不是React的主要内容,如果未能解决你的问题,请参考以下文章

将React + NodeJS + Express + MySQL应用程序部署到Heroku仅部署服务器而不是React

create-react-app + nodejs (express) 服务器

在heroku上部署Nodejs+Express+React+Webpack应用

React第六篇: 搭建React + Router + antd + nodejs + express框架搭建(nodejs做前后端server)

react+express项目

text 反向代理使用后端NodeJS Express创建React App Build