实现简易 React SSR 框架

实现简易 React SSR 框架

框架依赖

  • express
  • react
  • react-dom

创建一个 node server

使用 express 创建一个 node server

js 复制代码
import express from 'express'
import handlerSsr from './ssr'

const app = express()
const port = process.env.PORT || 3000

app.use(express.static('public'))

app.get('*' , (req, res) => {
  // 处理 SSR 逻辑
  return handlerSsr(req, res)
})

app.listen(port, () => {
  console.log(`Server started on http://localhost:${port}`)
});

创建一个根组件

js 复制代码
// client/App.js
import React from 'react';

function App(props) {
    return <div>Hello World!</div>;
}

export default App;

处理 SSR 逻辑

主要分为以下几个步骤:

  1. 解析请求:确定当前请求的URL和任何查询参数。
  2. 获取数据:对于动态内容,您可能需要从数据库或外部API获取数据。
  3. 渲染React组件树:使用收集到的数据渲染您的React组件树。
  4. 序列化HTML:将渲染后的React组件转换为静态HTML字符串。
  5. 发送响应:将最终的HTML字符串发送回浏览器。
js 复制代码
import App from './App'

export const handlerSsr = (req, res) => {
  // 处理请求
  const url = req.path

  const handleRequest = async () => {
      const data = await getDataPage(url);

      if (!data) {
          res.statusCode = 404;
          res.end('Not Found');
          return;
      }

      const html = renderPage(data);
      res.write(html);
      res.end();
  };

  // 获取数据(在真实场景中,这部分很可能是异步的)
  const getDataPage = async (url) => {
      // 模拟从数据库或API获取数据的行为
      switch (url) {
          case '/':
              return { title: 'Home', message: 'Welcome home!' };
          case '/about':
              return { title: 'About Us' };
          default:
              return null;
      }
  };

  // 渲染React组件树
  const renderPage = (data) => {
      const renderedContent = ReactDOMServer.renderToString(
          <App {...data} /> // 将数据作为props传递给App组件
      );

      return `
        <!doctype html>
        <html>
            <head>
                <meta charset=utf-8/>
                <title>${data.title}</title>
            </head>
            <body>
                <div id="root">${renderedContent}</div>
                <script type="text/javascript" src="index_bundle.js"></script>
            </body>
        </html>
    `;
  };

  handleRequest()
      .catch((err) => {
          console.error(err.stack);
          res.status(500).send('Something broke!');
      });

}
相关推荐
程序员小杰@22 分钟前
✨WordToCard使用分享✨
前端·人工智能·开源·云计算
larntin200243 分钟前
vue2开发者sass预处理注意
前端·css·sass
Enti7c1 小时前
利用jQuery 实现多选标签下拉框,提升表单交互体验
前端·交互·jquery
SHUIPING_YANG2 小时前
在Fiddler中添加自定义HTTP方法列并高亮显示
前端·http·fiddler
互联网搬砖老肖2 小时前
Web 架构之前后端分离
前端·架构
水银嘻嘻3 小时前
web 自动化之 selenium+webdriver 环境搭建及原理讲解
前端·selenium·自动化
寧笙(Lycode)3 小时前
为什么使用Less替代原始CSS?
前端·css·less
-Camellia007-3 小时前
TypeScript学习案例(1)——贪吃蛇
javascript·学习·typescript
m0_zj3 小时前
57.[前端开发-前端工程化]Day04-webpack插件模式-搭建本地服务器
前端·webpack·node.js
GoFly开发者3 小时前
GoFly企业版框架升级2.6.6版本说明(框架在2025-05-06发布了)
前端·javascript·vue.js