You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring WebSocket项目中SockJS与JQuery脚本无法执行排查

排查Spring WebSocket前端脚本不执行的问题

核心问题:模块脚本的作用域限制

你的脚本使用了type="module",这种模式下,脚本内的函数和变量默认处于模块私有作用域,不会暴露到全局作用域中:

  • body onload="connect()"是在全局作用域查找connect函数,自然找不到,导致页面加载时无法触发连接
  • 即使jQuery绑定了点击事件,如果模块脚本因作用域或导入问题未执行,sendMessage也无法触发

解决办法:将函数挂载到全局对象

修改模块脚本,把connect和sendMessage绑定到window对象,让全局作用域能访问到:

import { Stomp } from "@stomp/stompjs";
import SockJS from "sockjs-client";

let stompClient;
let chatId, userId, username;

// 挂载到window,允许全局调用
window.connect = function() {
  // 确保DOM元素已加载,再获取值
  chatId = document.getElementById("chatId").textContent;
  userId = document.getElementById("userId").textContent;
  username = document.getElementById("username").textContent;

  const socket = new SockJS("http://localhost:8080/websocket");
  stompClient = Stomp.over(socket);
  stompClient.connect({}, function(frame) {
    console.log("Connected: " + frame);
    stompClient.subscribe("/topic/chat/" + chatId, function(message) {
      console.log(JSON.parse(message.body));
    });
  });
};

window.sendMessage = function() {
  const message = {
    text: $("#messageText").val(),
    sender: {
      id: userId,
      username: username,
    },
    chat: {
      id: chatId,
    },
  };
  stompClient.send("/app/chat/" + chatId + "/send", {}, JSON.stringify(message));
};

$(function() {
  $("form").on("submit", function(e) {
    e.preventDefault();
  });
  $("#send").click(function() {
    window.sendMessage();
  });
});

其他可能的问题排查

1. 模块导入失败

打开浏览器开发者工具的控制台,查看是否有Failed to load module script类的错误:

  • 检查CDN链接是否有效:确认@stomp/stompjs@7.0.0和sockjs-client@1.1.4的ES模块入口可正常访问
  • 若导入失败,尝试更换CDN路径,比如将sockjs-client的导入改为https://cdn.jsdelivr.net/npm/sockjs-client@1.1.4/dist/sockjs.esm.min.js

2. DOM元素加载顺序问题

模块脚本默认延迟执行,但如果Thymeleaf渲染的DOM元素(如chatId、userId)尚未生成时脚本就执行,会导致变量值为空,但不会直接导致脚本不执行。建议将DOM元素的获取逻辑移到connect函数内部(如上例),确保在连接时已拿到正确的值。

3. WebSocket连接跨域问题

虽然配置了setAllowedOrigins("*"),但仍需确认:

  • 前端页面的域名/端口与后端localhost:8080是否一致,若不一致,检查控制台是否有跨域错误
  • SockJS连接地址是否正确,确保后端的/websocket端点已正确注册

内容的提问来源于stack exchange,提问作者Paincake-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:14:56