我有带有React Router的React App,用于客户端路由和Express Backend上的Rest API(React App正在使用API来获取数据)
目前,我配置为“ /”的Express路由转到包装React javascript文件的html文件,然后路由到后端API
我有用于客户端路由的React Router,它使路由变得复杂。
我想知道将我的应用程序分为两个更好:React App和Backend API并运行两个节点实例
最佳做法是什么?
这是我用于其中一个项目的简单server.js。
// server.js
import express from 'express'
import router from './api/router'
import { port } from './config'
express()
.use(express.static(__dirname + '/public'))
.use('/api', router)
.use('*', (_, res) => res.sendFile(__dirname + '/public/index.html'))
.listen(port, _ => console.log(`listening on ${port}`))
在public
内部是我的index.html,styles.css和bundle.js。 在app.use('*', ...)
,服务器将发送index.html。
一种更彻底的方法是编写一个使用react-router
的match
函数进行服务器端渲染的快速中间件,而不仅仅是在*
上发送index.html。 例如:
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from './route-config' // <-- react routes
export const renderPage = ({ url }, res) =>
match({ routes, location: url }, (err, redirect, renderProps) => {
if (err)
return res.status(500).send(err.message)
if (redirect)
return res.redirect(302, redirect.pathname + redirect.search)
if (renderProps) {
return res
.status(200)
.send(renderToString(<RouterContext { ...renderProps }/>))
}
res.status(404).send('Not found')
})
该方法使您能够正确处理404和重定向。