text/event-stream 服务器主动向前端推送以及如何使用post

创建时间:2023-08-04 16:43:04
栏目:前端

服务端

const http = require('http');
 ​
 http.createServer((req, res) => {
     res.writeHead(200, {
         'Content-Type': 'text/event-stream',
         'Cache-Control': 'no-cache',
         'Connection': 'keep-alive'
     });
 ​
     setInterval(() => {
         res.write('data: The server time is: ' + new Date() + '\n\n');
     }, 1000);
 ​
     req.connection.addListener('close', () => {
         console.log('SSE connection closed!');
     }, false);
 }).listen(8080);
 ​
 console.log('SSE Server listening on port 8080');

客户端

 const evtSource = new EventSource("http://localhost:8080/");
 ​
 evtSource.onmessage = function(event) {
     const serverTime = document.getElementById('serverTime');
     serverTime.innerHTML = event.data;
 };

关于不能使用post请求

npm i --save @rangermauve/fetch-event-source
 
 
import { fetchEventSource } from '@microsoft/fetch-event-source';
 
 
       let eventSource = fetchEventSource(Url, {
        method: 'POST',
        headers: {
          "Content-Type": 'application/json',
        },
        body: JSON.stringify(data),
        onmessage(event) {
          console.info(event.data);
        },
        onerror() {
          
        }
      })

联系我们

微信号:shidaping023