React App和Backend API最佳实践

时间:2016-06-03 06:15:59

标签: node.js reactjs express url-routing

我有React App和React Router用于客户端路由和Rest API通过Express Backend(React App正在使用API​​来获取数据)

目前,我的快速路由配置为' /'转到包含React javascript文件的html文件,然后转发到后端API

我已经为客户端路由做出了反应路由,它使路由变得复杂。

我想知道将我的应用程序分成两部分是否更好:React App和Backend API并运行两个节点实例

最佳做法是什么?

1 个答案:

答案 0 :(得分:3)

这是一个简单的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函数server-side rendering,而不是仅在*上发送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和重定向。

相关问题