javascript - 使用服务器路由 react 路由器浏览器历史记录

标签 javascript express reactjs react-router

我正在为客户端编写一个使用 react 并为服务器端使用 express 的 Web 应用程序。
我正在使用 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。如何合并这两者?

最佳答案

您必须在 * 之前定义 /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'))
})

关于javascript - 使用服务器路由 react 路由器浏览器历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799283/

相关文章:

arrays - 处理 Express 表单中的输入数组?

reactjs - 如何使用 Firebase/Firestore 将 componentDidMound 和 componentWillUnmount 转换为 UseEffect (React Hooks)?

reactjs - 当尝试映射react-redux状态时,state.get不是一个函数

reactjs - 有没有办法使 <TabbedShowLayout> 作为可编辑 View ?

javascript - 如何找到属于该按钮的 <div> 元素

javascript - 如何让固定div覆盖浏览器的滚动条?

javascript - 如何在 Express 的 res.redirect() 中使用变量?

javascript - 单击按钮时显示对话框 Jquery

javascript - 带有框架的 jQuery getScript 函数

node.js - 在 Node 中存储 mongoDB 的收集结果