浏览器无法连接到Springboot Websocket(sockjs)

3

我有一个运行在本地主机的SpringBoot服务器,端口为8080, 并且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类,并尝试使用null和http://localhost:3000(以及127.0.0.1)设置setAllowedOrigins:
@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)
})

有人能帮我吗?提前感谢。

2个回答

1
尝试使用 .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);

1
我已经尝试过(忘记在帖子中包含它),但浏览器仍然抱怨...这次是关于当ACCESS-CONTROL-ALLOW-ORIGIN设置为*时不允许set-credentials。 - alex

0

我没有用Spring(在服务器端)解决这个问题,但是我找到了一个解决方法。通过使用webpack(我使用的是create-react-app,默认使用webpack),可以将请求代理到“正确”的地址:

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

package.json上。解决了开发应用程序时的问题。但在生产环境中对您没有任何作用。但由于Web应用程序由Tomcat提供服务(编译版本即npm run build的结果放置在服务器上(src/main/resources/static),通过一些配置,它可以正常工作。

嗨,Alex,你能否提供更多细节,你具体做了什么。我的意思是,在使用client.connect连接时,你是否在属性中设置了代理。请告诉我,我也卡在同样的错误上了。 - A Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接