跳到主要内容

Websocket 跨域方案

准备


安装koakoa-staticws 依赖

yarn add koa koa-static ws -S 

语法


index.html

<!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>
<script>
let socket = new WebSocket("ws://localhost:4000");
socket.onopen = function(){
const data = {
title:"发送信息"
}
socket.send(JSON.stringify(data));
}
</script>
</body>
</html>

index.js

const Koa = require("koa");
const Path = require("path");
const WebSocket = require("ws");
const Static = require("koa-static");

const app = new Koa();
app.use(Static(__dirname,"./"));

const wss = new WebSocket.Server({ port: 4000 });
wss.on("connection", function (ws) {
ws.on("message", function (data) {
console.log(data);
const response = {
title:"回应"
}
ws.send(JSON.stringify(response));
});
});

app.listen(3000,function(){
console.log("服务启动成功!");
});

此时,浏览器访问localhost:3000/index.html就可以进行调试