-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssr.js
46 lines (40 loc) · 1.08 KB
/
ssr.js
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
//通过爬虫实现ssr
const express = require("express")
const puppeteer = require("puppeteer")
const commons = require("./src/utils/commons.js")
const Proxy = require("http-proxy-middleware")
const app = express()
const cacheUrl = {}
const proxy = Proxy({
target: commons.apiServer,
changeOrigin: true,
pathRewrite: {
['^'+commons.apiPrev]: ''
},
onError: function (err, req, res) {
// 监听proxy的onerr事件
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
}
})
//设置静态资源目录
app.use(express.static('public'))
app.use(commons.apiPrev, proxy)
app.get('*', async (req, res)=>{
if(cacheUrl[req.url]) {
return res.send(cacheUrl[req.url])
}
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('http://localhost:9093'+req.url, {
waitUntil: ['networkidle0']
})
const html = await page.content()
cacheUrl[req.url] = html
res.send(html)
})
app.listen(8081, ()=>{
console.log('spider ssr start')
})