node实现前后端通信

83 阅读1分钟

http通信

index.js

const http = require("http")

let data = { message: '信息1111' };

const server = http.createServer((req, res) => {
    if (req.url === '/getData') {
        res.writeHead(200, {
            // 'Content-Type': 'text/plain',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        });
        const data = {
            message: 'Hello World',
            date: new Date()
        };
        const json = JSON.stringify(data);
        res.end(json);
    }
});

server.listen(3535, () => {
    console.log('运行0000');
});

终端执行node index.js命令运行服务端

index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="test()">点击</button>
    <script>
        const test = () => {
            console.log();
            fetch('http://127.0.0.1:3535/getData')
                .then(response => response.json())
                .then(data => console.log(data));
        }
    </script>
</body>

</html>

WebSocket通信

ws.js

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 6060 });

wss.on('connection', ws => {
    ws.on('message', message => {
        console.log('后端接收消息: %s', message);
    });

    ws.send('后端发送消息');
});

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="test()">ws点击</button>
    <script>
        const test = () => {
            let socket = new WebSocket('ws://localhost:6060')
            // 连接打开时触发
            socket.onopen = function (event) {
                console.log('连接已打开');
                socket.send('4444');
            };

            // 接收到消息时触发
            socket.onmessage = function (event) {
                console.log('接收到消息: ' + event.data);
            };

            // 连接关闭时触发
            socket.onclose = function (event) {
                console.log('连接已关闭');
            };

            // 连接发生错误时触发
            socket.onerror = function (error) {
                console.log('WebSocket错误: ' + error.message);
            };
        }
    </script>
</body>

</html>