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

Browser not connecting to Springboot Websocket (sockjs)

我在 localhost:8080 上有一个 SpringBoot 服务器 运行 和 localhost:3000

上的 npm(服务于 React 应用程序)

每当我尝试与 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 class 并尝试 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("*") - 允许所有 ORIGINs:

/**
 * 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(在服务器端)解决这个问题,但我找到了解决方法。通过使用 webpack(我使用 create-react-app,它默认使用 webpack),可以简单地将请求代理到 "right" 地址:

  "proxy": "http://localhost:8080/"

package.json。解决了开发应用程序时的问题。但是在生产中不会为您做任何事情。但是由于 webapp 由 tomcat 提供服务(编译版本(即 npm run build 的结果被放置在服务器上(src/main/resources/static),通过一些配置它工作正常。