我正在使用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")
,但它不工作。
1条答案
按热度按时间2g32fytz1#
您的客户端连接到端口
8080
,但允许的源设置为5501
。在这种情况下,它们应该是相同的。