使用服务器路由反应路由器浏览器历史记录
React router browser history with server routing
我正在编写一个 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
。我怎样才能合并这两个?
您必须在 *
之前定义 /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'))
})
我正在编写一个 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
。我怎样才能合并这两个?
您必须在 *
之前定义 /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'))
})