2024-11-26 18:43:58 +08:00

34 lines
769 B
TypeScript

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './src/App';
const app = express();
// 静态文件服务
app.use(express.static('public'));
// 首页路由
app.get('/', (req, res) => {
const initialState = { name: 'John Doe22' };
const html = renderToString(<App initialState={initialState} />);
res.send(`<!DOCTYPE html>
<html>
<head>
<title>React SSR</title>
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<script type="module" src="/client.js"></script>
</body>
</html>`);
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});