首页 新闻 会员 周边 捐助

webflux接口前端接收问题

0
悬赏园豆:100 [待解决问题]

有没有懂SSE的大佬
我有一个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>

流光之中的主页 流光之中 | 初学一级 | 园豆:102
提问于:2024-08-27 09:57
< >
分享
所有回答(3)
0

在你提供的代码中,使用了 Spring WebFlux 来实现服务器推送事件(SSE),并在前端使用 EventSource 来接收这些事件。你提到在前端的 eventSource.onmessage 中打断点无法进入,这里有几个可能的原因和解决方案:

  1. 确认接口路径
    确保前端请求的 URL 正确无误,应该与你的后端接口路径一致。你在前端代码中使用的是:

const eventSource = new EventSource('http://127.0.0.1:8090/test/webflux');
请确保后端的接口路径是 /test/webflux,并且后端服务正在运行。如果你的接口路径是 /webflux,那么前端的 URL 应该改为:

const eventSource = new EventSource('http://127.0.0.1:8090/webflux');
2. CORS 问题
如果前端和后端在不同的端口或域上运行,可能会遇到跨域资源共享(CORS)问题。确保后端允许来自前端的请求。你可以在 Spring Boot 配置中添加 CORS 设置,例如:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径
.allowedOrigins("http://127.0.0.1:8090") // 允许的源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
.allowCredentials(true);
}
}
3. 检查网络请求
使用浏览器的开发者工具(通常按 F12 打开),切换到 "Network" 标签,查看请求是否成功。检查以下几点:

请求的状态码是否为 200。
响应的内容类型是否为 text/event-stream。
是否有任何错误信息或警告。
4. 后端代码确认
确保你的后端代码没有其他问题。你可以在 streamEvents 方法中添加一些日志,确认方法确实被调用。例如:

@GetMapping(value = "/webflux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamEvents() {
System.out.println("Stream started");
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> "data: Message " + sequence + "\n\n");
}
5. 浏览器支持
确保你使用的浏览器支持 EventSource。现代浏览器通常都支持,但如果你在某些较旧的浏览器中测试,可能会出现问题。

  1. 其他问题
    确保没有网络代理或防火墙阻止了请求。
    如果使用 HTTPS,确保证书是有效的。
    总结
    通过检查上述各个方面,你应该能够找到问题所在并解决它。如果问题仍然存在,请提供更多的错误信息或网络请求的详细信息,以便进一步分析。
kiry7769 | 园豆:59 (初学一级) | 2024-08-27 17:41

不会可以选择不答,ai我也会问,再说ai能解决100%的问题吗,他回答的我早就试了,能解决的话我早试过了,别拿鸡毛当令箭,博文全是这种,晦气

支持(0) 反对(0) 流光之中 | 园豆:102 (初学一级) | 2024-08-28 13:49
0

来自AI:

  1. 确保后端接口的URL是正确的。你的后端接口使用/webflux路径,在前端代码中你使用了/test/webflux路径。请确保这两个路径是匹配的。
  2. 检查浏览器控制台是否有错误信息。在前端代码中,你有一个onerror事件处理程序,用于处理EventSource失败。如果存在任何连接或其他错误,它将在控制台中显示错误信息。通过查看控制台输出,你可以获得更多的调试信息。
  3. 检查网络请求是否成功。在浏览器的网络面板中,你可以查看到对/webflux接口的网络请求。确认请求是否成功,并查看响应是否正确。如果请求失败或响应不正确,可能是后端接口的问题。
  4. 确保浏览器支持Server-Sent Events(SSE)。大多数现代浏览器都支持SSE,但确保你的浏览器是最新版本,并且支持该特性。你可以在浏览器的兼容性文档中查找相关信息。
Technologyforgood | 园豆:7231 (大侠五级) | 2024-08-28 07:55

不会可以选择不答,ai我也会问,再说ai能解决100%的问题吗,他回答的我早就试了,能解决的话我早试过了,别拿鸡毛当令箭,博文全是这种,晦气

支持(0) 反对(0) 流光之中 | 园豆:102 (初学一级) | 2024-08-28 13:49
0

webflux不熟悉,不过你这个前端代码没啥问题.要不你弄个node服务端,对比下看看浏览器的终端和网络信息有啥区别

const express = require('express');
const app = express();
const path = require('path');

var sequence = 0;

app.use(express.static(path.join(__dirname, 'pages')));

app.get('/webflux', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  setInterval(() => {
    res.write(`data: ${JSON.stringify({ message: 'Hello, World!' })}\n\n`);
    res.write(`data: Message ${sequence}\n\n`);
    sequence += 1;
  }, 1000);
});

app.listen(8090, () => {
  console.log('Server listening on port 8090');
});
<!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/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>
www378660084 | 园豆:682 (小虾三级) | 2024-08-28 17:17

后台应该没问题,能正常接收

支持(0) 反对(0) 流光之中 | 园豆:102 (初学一级) | 2024-08-30 18:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册