<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h4>我是html</h4>
<button id="btn">离开</button>
</body>
<script>
//判断当前浏览器是否支持SSE
let source = ''
if (!!window.EventSource) {
source = new EventSource('/sse')
} else {
throw new Error("当前浏览器不支持SSE")
}
//对于建立链接的监听
source.onopen = function (event) {
console.log("长连接打开", source.readyState)
}
//对服务端消息的监听
source.onmessage = function (event) {
console.log("收到长连接信息", JSON.parse(event.data))
}
//对断开链接的监听
source.onerror = function (event) {
console.log(source.readyState, "长连接中断")
}
/******************************************************************************************
页面卸载前发送请求
******************************************************************************************/
function leave(url, method) {
let para = {
method: method,
}
if (method == 'POST') {
para = {
method: method,
headers: {
'Content-Type': 'application/json' // 设置请求头
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
}
}
fetch(url, para).then(response => {
return response.json()
}).then(res => {
console.log(res) // 处理数据
}).catch(error => {
console.error(error)
})
};
document.querySelector('#btn').onclick = function () {
//(默认是post请求,只能发送不会接受到信息)
const data = JSON.stringify({ name: '150' })
navigator.sendBeacon('/test', data)
}
window.addEventListener('beforeunload', function (event) {
//(默认是post请求,只能发送不会接受到信息)
const data = JSON.stringify({ name: '150' })
navigator.sendBeacon('/test', data)
});
</script>
</html>
后端node
const express = require('express') //引用框架
const app = express() //创建服务
const port = 8088 //项目启动端口
const path = require('path')
const rawBody = require('raw-body')
//设置跨域访问
app.all("*", function (req, res, next) {
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin", '*')
//允许的header类型
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
// 可以带cookies
res.header("Access-Control-Allow-Credentials", true)
if (req.method == 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
})
// 请求页面
app.get("/html", (req, res) => {
res.sendFile(path.join(__dirname, 'home.html'))
})
// 测试接口
app.get("/test", (req, res) => {
console.log('测试接口')
res.send(JSON.stringify({ a: 'GET请求' }))
})
let num = null
app.get("/sse", (req, res) => {
res.set({
'Content-Type': 'text/event-stream', //设定数据类型
'Cache-Control': 'no-cache',// 长链接拒绝缓存
'Connection': 'keep-alive' //设置长链接
})
clearInterval(num)
num = setInterval(() => {
// console.log("返回ing")
const data = {
message: `Current time is ${new Date().toLocaleTimeString()}`
}
res.write(`data: ${JSON.stringify(data)}\n\n`)
}, 5000)
})
//创建项目
app.listen(port, () => {
console.log(`项目启动成功-http://localhost:${port}`)
})