跳至主要內容

SSE

刘春龙原创...小于 1 分钟NodejsNestjs教程文档

使用

import { Controller, Get, Res, Sse, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { interval, map } from 'rxjs';
import { createReadStream } from 'fs';
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  @Get()
  index(@Res() res: any) {
    createReadStream("src/views/index.html").pipe(res);
  }

  @Sse('sse')
  sse() {
    return interval(50).pipe(map(() => ({ data: { hello: 'abcba' } })));
  }
}













 

 


前端去请求

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body {
            word-break: break-all;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        const box = document.querySelector('#box');
        const eventSource = new EventSource('/sse');
        eventSource.onmessage = ({ data }) => {
            const msg = JSON.parse(data).hello
            if (box.innerHTML.length > 700) {
                return eventSource.close()
            }
            box.innerHTML += msg
        };
    </script>
</body>

</html>
上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7