普通网友 2025-11-28 14:44 采纳率: 0%
浏览 7

webflux接口前端接收问题

我有一个webflux接口,后端正常运行,前端使用eventSource接收,打断点eventSource.onmessage无法进入,
后端代码

    @GetMapping(value = "/webflux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEvents() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> "data: Message " + sequence + "\n\n");
    }

前端代码


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EventSource Stream Example</title>
</head>
<body>
    <h1>Real-time Updates</h1>
    <div id="messages"></div>

    <script>
        // 创建 EventSource 实例,连接到 WebFlux 接口
        const eventSource = new EventSource('http://127.0.0.1:8090/test/webflux');

        // 当接收到消息时,将其渲染到页面
        eventSource.onmessage = function(event) {
            const messageElement = document.createElement('div');
            messageElement.textContent = event.data;
            document.getElementById('messages').appendChild(messageElement);
        };

        // 错误处理
        eventSource.onerror = function(event) {
            console.error("EventSource failed: ", event);
            // 在页面上显示错误消息
            const errorElement = document.createElement('div');
            errorElement.style.color = 'red';
            errorElement.textContent = 'An error occurred, check the console for details.';
            document.getElementById('messages').appendChild(errorElement);
        };
    </script>
</body>
</html>

  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2025-11-28 15:01
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    问题分析

    • 你使用 WebFlux 开发了一个接口,后端正常运行。
    • 前端使用 EventSource 接收数据,但打断点 eventSource.onmessage 无法进入。
    • 后端代码使用 @GetMapping 注解,路径为 /w(可能是 /w 后面还有其他路径)。

    解决方案

    1. 检查 EventSource 实例是否正确: 确保 eventSource 实例正确创建,并且连接成功。
    2. 检查后端接口是否正确: 确保后端接口 /w 正确配置,并且返回正确的数据。
    3. 检查浏览器的 CORS 配置: 如果前端和后端在不同域名下,需要配置 CORS(Cross-Origin Resource Sharing)才能正常通信。
    4. 检查 EventSource 的错误处理: EventSource 可能会抛出错误,导致 onmessage 函数无法进入。可以使用 onerror 事件来捕获错误。

    核心代码

    // 前端代码
    const eventSource = new EventSource('/w');
    eventSource.onmessage = (event) => {
      console.log(event.data);
    };
    eventSource.onerror = () => {
      console.error('Error occurred');
    };
    
    // 后端代码
    @GetMapping("/w")
    public Flux<String> getW() {
      return Flux.just("Hello, World!");
    }
    

    注意

    • EventSource 的连接是持久的,需要在前端和后端都正确配置。
    • CORS 配置需要在后端配置,具体方法根据后端框架不同而不同。
    • 错误处理需要在前端和后端都正确配置。
    评论

报告相同问题?

问题事件

  • 创建了问题 11月28日