-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
114 lines (98 loc) · 2.91 KB
/
Copy pathserver.js
File metadata and controls
114 lines (98 loc) · 2.91 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const exp = require('express')
const express = exp()
const renderer = require('vue-server-renderer').createRenderer()
const fs = require('fs')
const createApp = require('./dist/bundle.server.js')['default']
const DB = require('./better-sqlite3')
const bodyParser = require('body-parser')
const session =require('express-session');
express.use(bodyParser.json());
express.use(session({
secret:'secret',
resave:true,
saveUninitialized: true,
cookie:{
maxAge:1000*60*5
}
}))
const db = new DB('data.db');
// 设置静态文件目录
express.use('/', exp.static(__dirname + '/dist'))
// 客户端打包地址
const clientBundleFileUrl = '/bundle.client.js'
express.get('/getInfo',(req,res) => {
var artical = db.findAll('artical');
res.send(artical);
})
express.get('/content*',(req,res) => {
url = req.url.slice(9);
fs.readFile(`./dist/markdown/${decodeURI(url)}.md`,(err,data) => {
if(err)
res.status(400).send('error')
else
res.send(data);
})
})
express.get('/getAbout',(req,res) => {
fs.readFile('./dist/markdown/about.md',(err,data) => {
if(err)
res.status(500).send('500')
else
res.send(data);
})
})
express.get('/favicon.ico',(req,res) => {
res.sendFile('./public/logo.ico',{root:__dirname});
})
express.get('/admin',(req,res,next) => {
if(!req.session.Username)
res.redirect('/login')
else
next()
})
express.post('/login/admin/',(req,res) => {
var data = req.body;
if(data.Username == 'Demon' && data.Password == 'syj000603'){
req.session.Username = data.Username;
res.send('OK')
// res.status(302).send('/admin')
}else{
res.status(400).send('用户名或密码不正确')
}
})
// 响应路由请求
express.get('*', (req, res) => {
const context = { url: req.url }
// 创建vue实例,传入请求路由信息
createApp(context).then(app => {
let state = JSON.stringify(context.state)
renderer.renderToString(app, (err, html) => {
if (err) {
return res.redirect('/404')
}
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demon's blog</title>
<script>window.__INITIAL_STATE__ = ${state}</script>
<script src="${clientBundleFileUrl}"></script>
</head>
<body>
<div id="app">${html}</div>
</body>
</html>
`)
})
}, err => {
if(err.code === 404) {
// res.status(404).end('404 NotFound')
res.redirect('/404')
}
})
})
// 服务器监听地址
express.listen(8080, () => {
console.log('服务器已启动!')
})