作为标题国家,我有一个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"
在此先感谢您的帮助,如果您需要任何其他文件或有任何疑问,请随时与我们联系!
答案 0 :(得分:1)
使用app.use
时,顺序很重要。因为所有服务器路由都是在通往React构建的路由之前声明的,所以服务器路由将具有优先权。
考虑为服务器路由添加前缀,以使其与应由前端构建处理的请求区分开来(/api
是常见选择)。
另一种选择是为前端指定一条路由(可能是/app
)。您可以将某些GET
请求重定向到homeRoute
中的此路由,这样,如果有人从根URL访问您的网站,那么他们最终会出现在正确的位置(假设您没有其他{{1 }}您希望GET
处理的路由。
因此您可以将通配符homeRoute
的路径更改为如下所示:
GET
然后在“ homeRoutes”内部
app.get('/app*', (req, res) => {
res.sendfile(path.resolve(__dirname + "./client/build/index.html"));
})