使用SockJS从Agular连接到WebSocket时出错

问题描述

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

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

获取“ mylocalhost”网络:: ERR_CONNECTION_REFUSED

如果我使用Firefox,我的oppinon中会出现一个更详细的错误

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

这是我的WebSocketConfigClass:

    uploader := s3manager.NewUploader(sess)

    _,err = uploader.Upload(&s3manager.UploadInput{
        Bucket: aws.String("theBucket"),Key:    aws.String("my.file"),Body:   file,})

设置AllowedOrigings还不够吗?

这是连接方法

@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();
  }
}

更新:我尝试改用服务器发送的事件,但是当我打电话时,我收到相同的错误消息:

    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");

如果这是一个cors问题,为什么我可以在rest控制器中调用其他方法呢?

解决方法

不应该

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

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