【发布时间】:2021-12-31 14:52:55
【问题描述】:
只要我先加载 index.html,React Router 就可以在 Heroku 上为我的 MERN 应用程序工作。如果我直接转到地址栏中的路由(例如 mysite.com/products),客户端路由会失败。但是,从主页单击指向产品页面的链接是可行的。
这个问题一直是discussed extensively for many years,但我在我的环境中无法解决这个问题。策略已经演变,目前尚不清楚最好的情况是什么。
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",
"react-scripts": "^5.0.0"
我的项目结构是:
-
root-
backend:快递服务器 -
frontend: React 应用程序
-
我尝试将static.json 文件添加到项目根目录。
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
我还尝试在 Express 中处理路由回退。在我的所有路线之后,我有:
const __dirname = path.resolve()
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))
} else {
app.get('/', (req, res) => {
res.send('API is running...')
})
}
// error handling middleware
// define error-handling middleware last, after other app.use() and routes calls
app.use(notFound) // 404 errors
app.use(errorHandler) // other errors
// for all non-api requests, return index.html from the build directory
app.get('*'),
(req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
}
// server listener
const PORT = process.env.PORT || 6060
app.listen(PORT, () =>
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
)
我会很感激能深入了解我错过了什么。
【问题讨论】:
标签: reactjs express heroku react-router