【问题标题】:Spring websocket with VueJs - blocked by CORS带有 VueJs 的 Spring websocket - 被 CORS 阻止
【发布时间】:2020-06-15 00:32:05
【问题描述】:

我正在尝试寻找如何通过 WebSocket 连接 VueJs 和 Spring 的解决方案。

WebSocket 配置(春季)

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket")
                .setAllowedOrigins("http://localhost:8080")
                .withSockJS();
    }

我尝试了几个使用 .setAllowedOrigins("") 的选项,例如“*”、“http://localhost:8080”,或者不要使用它。

我的项目中也有 CORS conf。

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

在我的 CORS conf 中,我尝试了很多选项,但没有结果:(

最后是客户端连接(VueJs):

connect() {
      this.socket = new SockJS("http://localhost:8081/gs-guide-websocket");
      this.stompClient = Stomp.over(this.socket);
      this.stompClient.connect(
        {},
        frame => {
          this.connected = true;
          console.log(frame);
          this.stompClient.subscribe("/topic/chat/1", tick => {
            console.log(tick);
            this.received_messages.push(JSON.parse(tick.body).content);
          });
        },
        error => {
          console.log(error);
          this.connected = false;
        }
      );
    }

在我尝试过的所有事情上,我都收到了这个错误:

从源 'http://localhost:8080' 访问 XMLHttpRequest 在 'http://localhost:8080' 已被 CORS 策略阻止:响应中的 'Access-Control-Allow-Credentials' 标头的值是 '' 必须是 '当请求的凭据模式为“包含”时,为 true。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

有什么解决方案可以让它发挥作用吗?

仅供参考:

  • 春天: localhost:8081
  • VueJs: localhost:8080

感谢大家的帮助:)

【问题讨论】:

    标签: spring vue.js websocket


    【解决方案1】:

    我是如此接近。这里的一切都是正确的(当然不是为了生产)。

    CORS conf 中最后缺少的是将Allow credentials 设置为true。

    希望这篇文章对你有帮助:)

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2020-11-15
      • 2021-08-17
      • 2020-11-27
      • 2020-08-29
      • 2020-11-11
      • 2021-11-20
      • 2021-01-16
      • 2019-08-03
      相关资源
      最近更新 更多