【问题标题】:React router browser history with server routing使用服务器路由反应路由器浏览器历史记录
【发布时间】:2016-08-16 09:45:51
【问题描述】:

我正在编写一个 Web 应用程序,客户端使用 react,服务器端使用 express
我正在使用react-router (link) 路由客户端页面。
使用hashHistory 很简单而且效果很好,但现在我想使用browserHistory

正如react-router 教程中提到的,我需要告诉我的服务器期待客户端请求,因此当我们呈现客户端页面时,它将为index.html 提供服务。
我找不到一种方法来处理来自客户端的页面请求和服务器处理请求。

例如,我在路径/product 中有一个页面,但我也有一个用于服务器处理/authenticate 的端点。

react-router 教程中,它说要使用以下内容:

// server.js
// ...
// add path.join here
app.use(express.static(path.join(__dirname, 'public')))

// ...
app.get('*', function (req, res) {
  // and drop 'public' in the middle of here
  res.sendFile(path.join(__dirname, 'public', 'index.html'))
})

但是这种方式会导致每个请求(包括/authenticate)都将其发送回index.html。如何合并这两者?

【问题讨论】:

    标签: javascript express reactjs react-router


    【解决方案1】:

    您必须在 * 之前定义 /authenticate(这基本上是 Catch-All 并且必须放在最后)

    app.use(express.static(path.join(__dirname, 'public')))
    
    ap.get('/authenticate', function (req, res) {
      res.sendStatus(200)
    });
    
    // ...
    app.get('*', function (req, res) {
      // and drop 'public' in the middle of here
      res.sendFile(path.join(__dirname, 'public', 'index.html'))
    })
    

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 2017-10-19
      • 2021-11-01
      • 2017-05-27
      • 2019-12-15
      • 2021-10-27
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多