1.前端页

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
<div>
<label for="username">请输入用户名:</label>
<input type="text" id="username" placeholder="用户名">
</div>

<div>
<input type="button" value="连接" id="connect">
<input type="button" value="断开连接" id="disconnet" disabled="disabled">
</div>
<div id="chat"></div>

<div>
<label for="content">请输入聊天内容</label>
<input type="text" id="content" placeholder="聊天内容">
</div>
<input value="发送" type="button" id="send" disabled="disabled"></input>
<script>
var stompClient;
$(function () {
$("#connect").click(function () {
connect();
$("#send").click(function () {
stompClient.send("/app/hello",{},JSON.stringify({'name':$("#username").val(),'content':$("#content").val()}))
})
$("#disconnet").click(function () {
stompClient.disconnect();
setConnect(false);
})
})
})
function connect() {
if (!$("#username").val()) {
return;
}
var socketjs = new SockJS("http://localhost:8080/chat");
stompClient = Stomp.over(socketjs);
stompClient.connect({},function (frame) {
setConnect(true);
stompClient.subscribe("/topic/greetings", function (greeting) {
var msgContent = JSON.parse(greeting.body);
console.log(msgContent);
$("#chat").append("<div>"+msgContent.name+":"+msgContent.content+"</div>");
});
})
}

function setConnect(connected) {
$("#connect").prop("disabled", connected);
$("#disconnet").prop("disabled", !connected);
$("#send").prop("disabled", !connected);
}
</script>
</body>
</html>

后端配置原来的:

websocket 跨域问题_html

 项目自己可以自己访问,前后端分离后除了配置nginx的upgrate外还是会有跨域问题,

后面根据提示:

When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

修改如下后解决:

websocket 跨域问题_jar_02