目的: 建立socket-io 长连接, 客户端实现监听用户添加操作,添加后服务端返回最新的数据给客户端,取代了查询+添加接口,代码分为server和client端,如下所示:
const express = require('express');
// const cors = require('cors');
const { db } = require('../../Server/mysql_main');
const app = express();
// app.use(cors())
app.use(express.json())
// 解决socket-io跨域问题 && 接口跨域(也可使用cors)
app.all("*", function (req, res, next) {
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin", "*");
//允许的header类型
res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Accept,Content-type");
res.header("Access-Control-Allow-Credentials", true);
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8")
if (req.method.toLowerCase() == 'options')
res.sendStatus(200); //让options尝试请求快速结束
else
next();
});
app.listen(8087, () => {
console.log(`服务已启动,端口号为8087`);
})
let _result = ''
db.connect()
db.query('select * from user', (err, data) => {
if (err) console.log('查询失败')
else _result = JSON.stringify(data)
})
const io = require('socket.io')(3001, { cors: true });
io.on("connection", (socket) => {
socket.emit("serverSend", _result);
socket.on("add_user", (...args) => {
const { name, age, address } = args[0]
db.query(`insert into user (name, age, address) values ('${name}', '${age}', '${address}')`, (err, data) => {
if (err) return socket.emit('serverSend', null)
db.query('select * from user', (err, data) => {
if (err) console.log('查询失败')
socket.emit("serverSend", err ? null : JSON.stringify(data));
})
})
});
socket.on("disconnect", () => {
console.log('连接断开')
})
});
<!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>
<link rel="stylesheet" href="./table.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
</head>
<body>
<div style="display: flex;">
<div>
姓名:<input type="text" id="name">
年龄:<input type="text" id="age">
地址:<input type="text" id="address">
</div>
<button id="add" style="margin-left: 15px;">添加用户</button>
</div>
<div class="table">
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="module">
import { io } from "https://cdn.socket.io/4.3.2/socket.io.esm.min.js";
const socket = io("ws://localhost:3001");
socket.on("serverSend", (data) => {
console.log('更新来自server端的数据 --- >');
const _result = data ? JSON.parse(data) : []
renderTbody(_result)
});
const renderTbody = (data) => {
let str = ''
for (let i = 0; i < data.length; i++) {
str += `<tr>
<td>${data[i].name || '--'}</td>
<td>${data[i].age || '--'}</td>
<td>${data[i].address || '--'}</td>
</tr>`
}
document.querySelector('tbody').innerHTML = str
}
const BASE_URL = `http://localhost:8087`
const ADD_ELE = document.querySelector('#add')
ADD_ELE.addEventListener('click', function () {
const name = document.querySelector('#name').value
if(!name.trim()) {
alert('姓名不能为空')
return;
}
const age = document.querySelector('#age').value || ''
const address = document.querySelector('#address').value || ''
socket.emit("add_user", {
name,
age,
address
});
})
</script>
</body>
</html>