【发布时间】:2020-12-13 12:35:32
【问题描述】:
我的 React 应用程序在客户端渲染中运行良好。我正在尝试在我的应用程序中实现服务器端渲染以用于 SEO。
当我运行 server.js 文件时出现错误。
我该如何解决这个问题? Server.js
import path from 'path';
import fs from 'fs';
const PORT = 8080;
const app = express();
const router = express.Router();
app.use(express.json());
const serverRenderer = (req, res, next) => {
const content = ReactDOMServer.renderToString(
<Provider store={store}>
<PresistGate presist={presist}>
<StaticRouter location={req.url} context={{}}>
<App />
</StaticRouter>
</PresistGate >
</Provider>
);
fs.readFile(path.resolve('../dist/index.html'), 'utf8', (err, data) => {
if (err) {
console.error(err);
return res.status(500).send('An error occurred');
}
return res.send(data.replace('<div id="root"></div>', `<div id="root">${content}</div>`));
});
};
router.use('*', serverRenderer);
router.use(express.static(path.resolve(__dirname, '..', 'dist'), { maxAge: '30d' }));
// tell the app to use the above rules
app.use(router);
// app.use(express.static('./build'))
app.listen(PORT, () => {
console.log(`SSR running on port ${PORT}`);
});
【问题讨论】:
标签: reactjs express redux server-side-rendering redux-saga