添加vite 使用 SSE
This commit is contained in:
parent
75144f0871
commit
bf48417e51
40
index.js
40
index.js
@ -406,6 +406,46 @@ function index_get(req, res) {
|
||||
}
|
||||
|
||||
const app = expressWs(express()).app
|
||||
const ServerSentEventsClient = {}
|
||||
|
||||
// Server-Sent Events (发送版本号来决定是否接收更新?)
|
||||
app.use((req, res, next) => {
|
||||
if (req.get('Accept') === 'text/event-stream') {
|
||||
console.log('SSE 连接', req.path)
|
||||
res.set({
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive'
|
||||
})
|
||||
res.write('retry: 10000\n\n')
|
||||
res.write(`data: ${JSON.stringify({ fm: 'message', data: 'hello' })}\n\n`)
|
||||
res.write(`data: ${JSON.stringify({ fm: 'message', data: 'hellox' })}\n\n`)
|
||||
if (!ServerSentEventsClient[req.path]) ServerSentEventsClient[req.path] = []
|
||||
ServerSentEventsClient[req.path].push({ req, res })
|
||||
req.on('close', () => {
|
||||
console.log('SSE 断开', req.path)
|
||||
let index = ServerSentEventsClient[req.path].findIndex(item => item.res === res)
|
||||
if (index !== -1) ServerSentEventsClient[req.path].splice(index, 1)
|
||||
})
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
// SEE DEMO
|
||||
app.route('/demo').get((req, res) => {
|
||||
res.send(`<!DOCTYPE html>
|
||||
<html><body><h1>SSE Express</h1>
|
||||
<script type="text/javascript">
|
||||
const source = new EventSource("/api/see");
|
||||
source.onmessage = e => {
|
||||
console.log(JSON.parse(e.data))
|
||||
document.body.innerHTML += e.data + "<br>"
|
||||
};
|
||||
</script></body></html>
|
||||
`)
|
||||
})
|
||||
|
||||
app.use(express.json())
|
||||
app.use(express.urlencoded({ extended: false }))
|
||||
app.use(session({ secret: 'kana', name: 'sid', resave: false, saveUninitialized: false, cookie: { maxAge: 180 * 24 * 3600000 }, store: session_store }))
|
||||
|
@ -25,6 +25,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.0"
|
||||
"nodemon": "^3.1.0",
|
||||
"vite": "^5.2.11"
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user