我正在尝试创建具有服务器端渲染功能且对Google搜索引擎友好的React应用程序。如文档所述,我创建了一个简单的NodeJS服务器,该服务器将React组件呈现为字符串,获取index.html
模板,并将根标记替换为呈现的字符串。如果我从浏览器中打开页面,一切都很好,但是当我看到页面源时,仅存在根标记(例如index.html
也具有相同的源)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id="application"></div>
<script src="bundle.js"></script>
</body>
</html>
NodeJS服务器
import fs from 'fs';
import path from 'path';
import express from 'express';
import React from 'react';
import { renderToString, } from 'react-dom/server';
import Application from './../components/application';
const appx = express();
const port = process.env.PORT || 8080;
const publicPath = express.static(path.join(__dirname, './../'));
const indexPath = path.join(__dirname, './../index.html');
appx.use(publicPath);
appx.get('*', (request, response) => {
const reactDOM = renderToString(<Application/>);
fs.readFile(indexPath, 'utf8', function (error, content) {
if (error) {
return response.status(500).send('Oops!');
}
let html = content.replace(`<div id="application"></div>`, `<div id="application">${reactDOM}</div>`);
return response.status(200).send(html);
});
});
appx.listen(port);
为什么NodeJS不发送实际内容?
PS。如果在console.log(html)
之前将return response.status(200).send(html);
添加到服务器代码,则会显示消息
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id="application"><div data-reactroot=""><p>React server side rendering</p></div></div>
<script src="bundle.js"></script>
</body>
</html>
答案 0 :(得分:0)
我强烈建议您使用next.js框架来完成此任务。他们已经建立了一个了不起的框架,可以通过react解决服务器端渲染的复杂性,并且拥有丰富的文档。这是在反应中进行服务器端渲染的方法。 Nextjs Link
答案 1 :(得分:0)
在不检查整个源代码的情况下不确定确切原因。但您的描述中未提及的一件事可能值得检查:
您是否完全在客户端JS中使用ReactDOM.hydrate
?我们正在使用它来确保React组件可以正确呈现(附加事件监听器等)。