Spring - Sock.js - websockets:被 CORS 策略阻止
Spring - Sock.js - websockets: blocked by CORS policy
我正在 Spring 客户端应用程序上使用 sock.js
+ stomp.js
应用程序实现 websockets。
尝试连接时出现错误:
Access to XMLHttpRequest at 'http://localhost:8080/ws/tracker/info?t=...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在我的 WebsocketConfiguration
中:
@Configuration
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic/", "/queue/");
registry.setApplicationDestinationPrefixes("/app");
}
}
客户端库:
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.4.0/sockjs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
客户端连接:
var socket = new SockJS('http://localhost:8080/websocket/tracker');
我已经在一个早期的项目中实现了 websockets,所以这都是从它那里复制的,虽然我不记得(也找不到)如何解决这个错误。
检查是否有ClientForwardController
,映射应该是这样的:
@GetMapping(value = {"/{path:[^\.]*}", "/{path:^(?!websocket).*}/**/{path:[^\.]*}"})
public String forward() {
return "forward:/";
}
我正在 Spring 客户端应用程序上使用 sock.js
+ stomp.js
应用程序实现 websockets。
尝试连接时出现错误:
Access to XMLHttpRequest at 'http://localhost:8080/ws/tracker/info?t=...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在我的 WebsocketConfiguration
中:
@Configuration
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic/", "/queue/");
registry.setApplicationDestinationPrefixes("/app");
}
}
客户端库:
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.4.0/sockjs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
客户端连接:
var socket = new SockJS('http://localhost:8080/websocket/tracker');
我已经在一个早期的项目中实现了 websockets,所以这都是从它那里复制的,虽然我不记得(也找不到)如何解决这个错误。
检查是否有ClientForwardController
,映射应该是这样的:
@GetMapping(value = {"/{path:[^\.]*}", "/{path:^(?!websocket).*}/**/{path:[^\.]*}"})
public String forward() {
return "forward:/";
}