【FAQ】Springboot3+Vue3在进行WebSocket通讯时出现No mapping for GET或者是404
参考:在 Spring Boot 中整合、使用 WebSocket - spring 中文网 (springdoc.cn)
===============================
原代码(此时前端访问后端,后端会出现:
No mapping for GET /wspath
)
前端相关代码:
let socket: WebSocket | null = null const socketURL = `ws://127.0.0.1:8084/wspath/${userId}` socket = new WebSocket(socketURL.toString()) // 建立ws连接
后端代码:
1.config配置
@Configuration @EnableWebSocket public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
2.实现类(类中的方法我没粘贴进来)
@Component @Slf4j @ConditionalOnClass(value = WebSocketConfig.class) @CrossOrigin(origins = "*", maxAge = 3600) @ServerEndpoint(value = "/wspath/{userId}") public class MyWebSocketHandler {}
======================
看了一下是没有注册WebSocket,但是我已经使用了@Component进行注解,按理Spring会自动扫描注册,但是就是没有成功,搞不明白。
所以我们手动注册一下即可。
======================
前端代码不变,后端只修改config的配置文件:
@Configuration @EnableWebSocket public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { ServerEndpointExporter exporter = new ServerEndpointExporter(); exporter.setAnnotatedEndpointClasses(MyWebSocketHandler.class); return exporter; } }
如此,就可以接收到前端的建立请求了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2023-01-16 安装完Git鼠标右键不显示或者打不开Git Bash Here和Git GUI Here的问题