随着前端技术的不断发展,前端渲染方式也不断地发生变化。在单页应用(SPA)流行的时代,前端渲染主要依靠 JavaScript 来完成。但是,随着 SEO 和首屏渲染的重要性日益凸显,服务端渲染(SSR)也成为了一种重要的前端渲染方式。
Node.js 作为一种后端 JavaScript 运行环境,可以方便地实现服务端渲染。本文将详细介绍 Node.js 中如何实现服务端渲染,包括以下内容:
- 什么是服务端渲染
- 为什么需要服务端渲染
- Node.js 中如何实现服务端渲染
- 示例代码
什么是服务端渲染
服务端渲染是指在服务器端生成 HTML、CSS 和 JavaScript,并将其发送给浏览器,浏览器只需要负责展示页面即可。与客户端渲染不同,服务端渲染的页面在浏览器中的展示速度更快,且更有利于 SEO。
为什么需要服务端渲染
服务端渲染的优势在于:
- 更快的首屏渲染速度:服务端渲染可以在服务器端生成 HTML、CSS 和 JavaScript,减少浏览器的渲染时间,从而提高页面的首屏渲染速度。
- 更好的 SEO:搜索引擎可以通过爬取 HTML 文件来了解页面的内容,从而提高网站的排名。
- 更好的用户体验:服务端渲染可以减少页面的白屏时间,提高用户体验。
在 Node.js 中实现服务端渲染的方式有很多种,这里介绍两种常用的方式:使用模板引擎和使用 React。
使用模板引擎
模板引擎是一种将数据和模板合并生成 HTML 的工具。在 Node.js 中,常用的模板引擎有 EJS、Handlebars、Pug 等。
下面以 EJS 为例,介绍如何在 Node.js 中使用模板引擎实现服务端渲染。
- 安装 EJS
使用 npm 安装 EJS:
npm install ejs
- 创建模板文件
创建一个 EJS 模板文件 index.ejs,并将需要渲染的数据传入模板文件中:
// www.javascriptcn.com code example <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <p><%= content %></p> </body> </html>
- 创建 Node.js 服务器
创建一个 Node.js 服务器,将 EJS 模板渲染成 HTML 并返回给客户端:
// www.javascriptcn.com code example
const http = require('http');
const fs = require('fs');
const ejs = require('ejs');
const server = http.createServer((req, res) => {
// 读取模板文件
fs.readFile('index.ejs', 'utf8', (err, template) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
return;
}
// 渲染模板
const html = ejs.render(template, {
title: 'Hello EJS',
content: 'Welcome to EJS world!'
});
// 返回 HTML
res.setHeader('Content-Type', 'text/html');
res.end(html);
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});- 运行服务器
在命令行中运行 Node.js 服务器:
node server.js
在浏览器中访问 http://localhost:3000,即可看到渲染后的 HTML 页面。
使用 React
React 是一种流行的前端框架,也可以用于服务端渲染。在 Node.js 中使用 React 实现服务端渲染的方式如下:
- 安装 React 和 React DOM
使用 npm 安装 React 和 React DOM:
npm install react react-dom
- 创建 React 组件
创建一个 React 组件 App.js:
// www.javascriptcn.com code example
import React from 'react';
function App(props) {
return (
<html>
<head>
<meta charSet="UTF-8" />
<title>{props.title}</title>
</head>
<body>
<h1>{props.title}</h1>
<p>{props.content}</p>
</body>
</html>
);
}
export default App;- 创建 Node.js 服务器
创建一个 Node.js 服务器,将 React 组件渲染成 HTML 并返回给客户端:
// www.javascriptcn.com code example
const http = require('http');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./App');
const server = http.createServer((req, res) => {
// 渲染 React 组件
const html = ReactDOMServer.renderToString(
<App title="Hello React" content="Welcome to React world!" />
);
// 返回 HTML
res.setHeader('Content-Type', 'text/html');
res.end(html);
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});- 运行服务器
在命令行中运行 Node.js 服务器:
node server.js
在浏览器中访问 http://localhost:3000,即可看到渲染后的 HTML 页面。
示例代码
完整的示例代码可以在 GitHub 上找到:
这些示例代码可以帮助你更好地理解 Node.js 中如何实现服务端渲染。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d3a564a941bf71346f4fb0