gpt4 book ai didi

spring - 浏览器未连接到 Springboot Websocket (sockjs)

转载 作者:行者123 更新时间:2023-12-05 06:35:42 26 4
gpt4 key购买 nike

我有一个在 localhost:8080 上运行的 SpringBoot 服务器和本地主机上的 npm(服务于 React 应用程序):3000

每当我尝试建立到 spring 的 websocket 连接时,这会显示在浏览器的控制台上 (Firefox Nightly):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/ws/info?t=1522629329791.
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match
‘http://localhost:8080/ws/info’).

我创建了一个 WebSocketMessageBrokerConfigurer 类并尝试将 setAllowedOrigins 宽度设置为 null 和 http://localhost:3000(和 127.0.0.1 以及):

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:3000")
.withSockJS();
}

REST 请求工作正常,我什至在一个简单的节点脚本中连接到 websocket,但在浏览器中我没有运气。这就是我在浏览器中的连接方式(与脚本中的相同):

import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
...
let ws = new SockJS('http://localhost:8080/ws/');
let client = Stomp.over(ws);
client.connect({'some-header': 'some-data'}, (success) => {
//client.subscribe(...
}, (error) => {
console.log(error)
})

有人可以帮助我吗?提前致谢。

最佳答案

尝试 .setAllowedOrigins("*") - 允许所有 ORIGIN:

/**
* Configure allowed {@code Origin} header values. This check is mostly designed for
* browser clients. There is nothing preventing other types of client to modify the
* {@code Origin} header value.
*
* <p>When SockJS is enabled and origins are restricted, transport types that do not
* allow to check request origin (JSONP and Iframe based transports) are disabled.
* As a consequence, IE 6 to 9 are not supported when origins are restricted.
*
* <p>Each provided allowed origin must start by "http://", "https://" or be "*"
* (means that all origins are allowed). By default, only same origin requests are
* allowed (empty list).
*
* @since 4.1.2
* @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a>
* @see <a href="https://github.com/sockjs/sockjs-client#supported-transports-by-browser-html-served-from-http-or-https">SockJS supported transports by browser</a>
*/
StompWebSocketEndpointRegistration setAllowedOrigins(String... origins);

关于spring - 浏览器未连接到 Springboot Websocket (sockjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49604235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com