如何在Sping Boot 中通过STOMP连接WebSocket时修复CORS错误?

ix0qys7i  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(140)

我正在使用Sping Boot 和JavaScript构建一个聊天应用程序,但我收到一个错误:

Access to XMLHttpRequest at 'http://localhost:8080/ws/chat/info?t=1689700945725' ↗ from origin 'http://localhost:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

字符串
这是我的代码…
SecurityConfig:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers("/user/**").permitAll()
                    .anyRequest().authenticated()
            )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}


StompConfig:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws/chat").setAllowedOrigins("http://localhost:5501").withSockJS();
}

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


客户端:

var socket = new SockJS('http://localhost:8080/ws/chat', null, {
    headers: {
        Authorization: 'Bearer ' + jwt
    }
});
stompClient = Stomp.over(socket);
stompClient.connect({}, onConnected, onError);


我试过使用setAllowedOriginPatterns("http://localhost:5501"),但它不工作。

2g32fytz

2g32fytz1#

您的客户端连接到端口8080,但允许的源设置为5501。在这种情况下,它们应该是相同的。

相关问题