-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.prod.ts
108 lines (91 loc) · 3.48 KB
/
server.prod.ts
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
import type { RenderType } from '~/types'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { UTC2Date } from '@lincy/utils'
import compression from 'compression'
import cookieParser from 'cookie-parser'
import express from 'express'
import { createProxyMiddleware } from 'http-proxy-middleware'
import logger from 'morgan'
import requestIp from 'request-ip'
import serveStatic from 'serve-static'
import apiDomain from './src/api/url'
export async function createServer() {
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const resolve = (p: string) => path.resolve(__dirname, p)
const template = fs.readFileSync(resolve('client/index.html'), 'utf-8')
const manifest = JSON.parse(fs.readFileSync(resolve('client/.vite/ssr-manifest.json'), 'utf-8'))
const app = express()
logger.token('remote-addr', (req) => {
return requestIp.getClientIp(req) || 'unknown'
})
logger.token('date', () => {
return UTC2Date(undefined, 'yyyy-mm-dd hh:ii:ss.SSS')
})
// Node.js 日志中间件
app.use(
logger('[:remote-addr] [:date] ":method :url" :status :res[content-length] ":referrer"', {
skip(req) {
const skipExt = ['.webmanifes', '.php', '.txt', '.map', '.js', '.css', '.png', 'jpg', '.jpeg', '.gif', '.ttf', '.woff2', '.ico']
return skipExt.some((ext) => {
return req.url.includes(ext)
})
},
}),
)
// Node.js 压缩中间件
app.use(compression())
// Node.js 代理中间件, 也可以在 nginx 直接配置, 那么将不会走这里的代理中间件
app.use(
createProxyMiddleware({
target: apiDomain,
changeOrigin: true,
pathFilter: ['/api/**'],
pathRewrite: {
'^/api': '/api',
},
on: {
proxyReq(proxyReq, req) {
proxyReq.setHeader('x-real-ip', requestIp.getClientIp(req) || 'unknown')
},
},
}),
)
// Node.js 静态资源中间件
app.use(
serveStatic(resolve('client'), {
index: false,
}),
)
// 解析 application/json 中间件
app.use(express.json({ limit: '50mb' }))
// 解析 application/x-www-form-urlencoded 中间件
app.use(express.urlencoded({ limit: '50mb', extended: true }))
// 解析 cookies 中间件
app.use(cookieParser())
app.use('*', async (req, res) => {
try {
// const url = req.originalUrl.replace('/test/', '/')
const url = req.originalUrl
// @ts-expect-error 未编译, 目录不对, 该文件不存在
const render = (await import('./server/entry-server.js')).render
const { html: appHtml, preloadLinks, headTags } = await render(url, manifest, req) as RenderType
const html = template
.replace('<!--preload-links-->', preloadLinks)
.replace('<!--app-html-->', appHtml)
.replace('<!--head-tags-->', headTags)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
}
catch (e: unknown) {
const err = e as Error
console.log(err.stack)
res.status(500).end(err.stack)
}
})
return { app }
}
const port = 7777
createServer().then(({ app }) => app.listen(port, () => {
console.log(`监听: http://localhost:${port}`)
}))