SSR是 Server-Side Rendering(服务器端渲染)的缩写,简单的理解就是将平时写的组件,页面通过服务器生成html字符串,再发送到浏览器,最后将静态标记,混合为客户端上交互的应用程序
接下来我们使用node简单的写个服务端渲染的例子:
首先创建一个项目文件夹:
1,初始化项目:yarn init -y
2,下载对应的依赖包:
yarn add -D koa koa-router koa-ejs
3,在项目文件夹中创建app.js和一个template文件夹
4,app.js的代码
const Koa = require('koa');
const Router = require('koa-router');
const path = require('path');
const ejs = require('koa-ejs');
const app = new Koa()
const router = new Router()
ejs(app, {
root: path.join(__dirname, 'template'),
layout: false,
viewExt: 'ejs',
cache: false,
debug: false
});
router.get('/', async ctx => {
await ctx.render('index', {
title: 'test',
arr: [
{name: '小红', age: 12},
{name: '小明', age: 23}
]
})
})
app.use(router.routes())
app.listen(3000)
然后在template中创建index.ejs,index.ejs中的代码为:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= title %></title>
</head>
<body>
<div>
<%= title %>
</div>
<ul>
<% arr.forEach(item => { %>
<li>
<span><%= item.name %></span>
<span><%= item.age %></span>
</li>
<%}) %>
</ul>
</body>
</html>
接下来我们使用node app.js运行项目,在本地浏览器访问:http://localhost:3000/,就会看到如下页面
这个页面就是我们通过服务器渲染的页面
通过服务器渲染的页面的优点和缺点可以看下面这个网址:
https://www.jianshu.com/p/fcb98533bc18