React App和后端API最佳实践

我有反应路由器的客户端路由React应用程序和快速后端rest API(React应用程序正在使用API​​来获取数据)

目前我configuration为“/”的Expresspath转到包装React JavaScript文件的HTML文件,并在路由到后端API

我有反应路由器为客户端路由,使路由变得复杂。

我想知道是否将我的应用程序分为两个更好:React App和后端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-routermatch函数来进行服务器端的渲染,而不是只发送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和redirect。