在B/S场景中,通常我们前端主动访问后端可以使用axios,效果很理想,而后端要访问前端则不能这样操作了,可以考虑SSE、websocket和gRPC等方式,实时和性能均有保障。
下面给出一个简单的例子,后端是node+express,前端是html+javascript(jquery+axios) 实现一个简单的web聊天室。
不说废话,直接上代码:
const stringRandom = require("string-random");
const express = require('express');
const app = express();
var msgs=[];
var clients=[];
app.use('/', express.static('./'));
app.get('/events', (req,res)=>{
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' });
res.write(`data: ${JSON.stringify(msgs)}\n\n`);
let clientid=stringRandom(32, { letters: 'ABCDEF' })
clients.push({ "clientid":clientid, "res":res });
req.on('close', () => { clients = clients.filter(item => (item.clientid != clientid)); });
});
app.post('/sendmsg',express.json(), (req,res)=>{
msgs.push(req.body);
res.json({"code":200});
clients.forEach(client=>{ client.res.write(`data: ${JSON.stringify(req.body)}\n\n`) });
});
app.listen(3000, () => { console.log(`极简聊天室服务启动`); })
<!DOCTYPE html>
<html>
<head>
<title>极简聊天室</title>
<meta charset="utf-8">
<script src="jquery-3.6.1.min.js"></script>
<script src="axios.min.js"></script>
</head>
<body>
<input id="msg"></input><button id="send" onclick=sendmsg()>发送</button>
<ul id="msgs">
</ul>
<script>
var uid;
let reg = new RegExp("(^|&)" + "uid" + "=([^&]*)(&|$)","i");
let r = location.search.substr(1).match(reg);
uid=(r!=null)?decodeURI(r[2]):"me";
const evtSource = new EventSource("http://localhost:3000/events");
evtSource.addEventListener('message', function(event) {
let jvar=JSON.parse(event.data);
if (jvar instanceof Array) {
jvar.forEach(item=>{ $("#msgs").append(`<li>${item.uid} 说: ${item.msg}</li>`) } )
}
else { $("#msgs").append(`<li>${jvar.uid} 说: ${jvar.msg}</li>`) }
})
function sendmsg() { axios.post("http://localhost:3000/sendmsg",{"uid":uid,"msg":$("#msg").val()}).then(()=>$("#msg").val("")) }
</script>
</body>
</html>
浏览器访问效果如下: