【问题标题】:Error while connecting to WebSocket from Agular with SockJS使用 SockJS 从 Agular 连接到 WebSocket 时出错
【发布时间】:2020-12-28 01:23:02
【问题描述】:

我尝试在我的 Angular 项目中实现 WebSocket-Connection。对于后端,我使用 SpringBoot。 我找到了一个教程并完成了所有步骤。这是教程的链接 https://www.codesandnotes.be/2020/03/31/websocket-based-notification-system-using-spring/

但是当我尝试连接到 WebSocket 时总是收到错误消息。这是来自 google chrome 的错误消息:

GET "mylocalhost" net::ERR_CONNECTION_REFUSED

如果我使用 firefox,我会得到一个更详细的错误:

跨域请求被阻止:同源策略不允许读取远程资源...

这是我的 WebSocketConfigClass:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Override
  public void configureMessageBroker(MessageBrokerRegistry registry) {
      registry.enableSimpleBroker("/notification");
      registry.setApplicationDestinationPrefixes("/swns");
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
      registry.addEndpoint("/notifications")
              .setAllowedOrigins("*")
              .withSockJS();
  }
}

设置 AllowedOrigings 还不够吗?

这里是连接方法:

    connectClicked() {
    if (!this.client || this.client.connected) {
        this.client = new RxStomp();
        this.client.configure({
            webSocketFactory: () => new SockJS("http://localhost:8080/notifications"),
            debug: (msg: string) => {
                console.log(msg);
            }
        });
        this.client.activate();

        this.watchForNotifications();

        console.info("connected!");
    }
}

更新:我尝试使用服务器发送的事件,但是当我调用时我得到了相同的错误消息:

const source = new EventSource("http://localhost:8080/stream-sse");

这是我的控制器中的代码:

 @GetMapping("/stream-sse")
  public Flux<ServerSentEvent<String>> streamEvents() {
    return Flux.interval(Duration.ofSeconds(1))
           .map(sequence -> ServerSentEvent.<String>builder()
                   .id(String.valueOf(sequence))
                   .event("periodic-event")
                   .data("SSE - " + LocalTime.now().toString())
                   .build());
}

如果有 cors 问题,为什么我可以在 rest 控制器中调用其他方法。

【问题讨论】:

    标签: angular spring-boot websocket sockjs


    【解决方案1】:

    不应该

    new SockJS("http://localhost:8080/notifications")
    

    成为

    new SockJS("ws://localhost:8080/notifications") for http
    new SockJS("wss://localhost:8080/notifications") for https
    

    【讨论】:

    • SockJS 不支持 ws 或 wss protocall
    猜你喜欢
    • 2015-08-10
    • 2017-11-20
    • 2018-09-11
    • 2021-06-21
    • 2013-03-31
    • 2013-08-16
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多