# 搭建
- 使用express创建服务渲染一个vue实例并返回
const Vue = require('vue')
const server = require('express')()
const renderer = require('vue-server-renderer').createRenderer()
server.get('*', (req, res) => {
const app = new Vue({
template: `<div>访问的URL是 {{ url }}</div>`,
data: {
url: req.url
}
})
renderer.renderToString(app).then(html => {
res.end(
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>${html}</body>
</html>`
)
}).catch(err => {
res.status(500).end('Internal Server Error')
})
})
app.listen(5000, function () {
console.log('app is running~');
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- 使用html模板
<!-- 创建一个模板文件 ./src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
{{{meta}}}
</head>
<body>
<!--vue-ssr-outlet-->
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
const express = require('express')
const Vue = require('vue')
const fs = require('fs')
const path = require('path')
const renderer = require('vue-server-renderer').createRenderer({
template: fs.readFileSync(path.resolve(__dirname, './src/index.html'), 'utf-8')
})
const app = express()
app.get('*', (req, res) => {
const app = new Vue({
template: `
<div>当前访问的URL是:{{url}}</div>
`,
data: {
url: req.url
}
})
const context = {
title: 'SSR',
meta: `
<meta name="description" content="my blog">
`
}
renderer.renderToString(app, context).then(html => {
res.end(html)
}).catch(err => console.log(err))
})
app.listen(5000, function () {
console.log('app is running~');
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
← 基础知识