【问题标题】:React Router on HerokuHeroku 上的反应路由器
【发布时间】: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


    【解决方案1】:

    解决:

    1. 将错误处理中间件放在最后。
    2. 设置构建目录的静态路径
    3. 将所有非 API 路由定向到 index.html

    不需要static.json。另外,请确保在 Heroku 配置变量中将 process.env.NODE_ENV 设置为 production

    const __dirname = path.resolve()
    
    if (process.env.NODE_ENV === 'production') {
      app.use(express.static(path.join(__dirname, '/frontend/build')))
    
      app.get('*', (req, res) =>
        res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
      )
    } 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
    
    // 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
      )
    )
    

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 2017-07-23
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多