使用服务器路由验证路由器浏览器历史记录

时间:2016-04-22 16:45:30

标签: javascript express reactjs react-router

我正在为客户端使用react编写Web应用程序,为服务器端编写express 我正在使用react-routerlink)路由客户端页面 使用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。我该如何合并这两个?

1 个答案:

答案 0 :(得分:3)

你必须在/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'))
})