Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: simple ssr #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
node_modules
package-lock.json
serverBack.js
serverBack.js

.DS_Store
/dist

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
39 changes: 38 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
@@ -1 +1,38 @@
// TODO 监听3000端口,便于执行test
import express from 'express'
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'

const server = express()

server.get('/', async function (req, res) {
const message = req.query.message ?? 'Vue SSR Example'

const app = createSSRApp({
data: () => ({ message }),
template: `<div>{{message}}</div>`
})

const html = await renderToString(app)
.catch(err => {
// 处理错误,应该利用日志框架写下日志,这里用 console 代替
console.error(err)
res.status(500).send('抱歉,服务器出错了')
})

res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">${html}</div>
</body>
</html>
`)
})

server.listen(3000)

console.log("Server start at: http://127.0.0.1:3000")
Loading