我使用springboot-websocket和spring-stomp构建webscoket应用程序,并使用sockjs发送websocket请求,但出现错误 像这样:
Failed to load http://192.168.0.118:8090/endpointWisely/info?t=1539219338972: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.118:8099' is therefore not allowed access. The response had HTTP status code 405.
html代码在这里:
function connect() {
var socket = new SockJS('http://192.168.0.118:8090/endpointWisely'); //链接SockJS 的endpoint 名称为"/endpointWisely"
stompClient = Stomp.over(socket);//使用stomp子协议的WebSocket 客户端
var headers = {
'authorization':'bearer;eyJ0eXBlIjoiand0VG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJ4LXRlbmFudC1pZCI6MTE5NjU2MzE5Nzk5ODA4LCJ4LXVzZXItaWQiOiIxMTk2NTYzMjE2MTAyNDAiLCJpc3MiOiJhcGl1c2VyIiwiYXVkIjoiMTUyMzQ5NjY4MzMzOSIsImV4cCI6MTUzODIzNjc3OCwibmJmIjoxNTM4MTg2NzEzfQ.hjA9_WwplrCsYsTEYJXRBJI5e5OZzX4-NzDXuaBo8VQ'
};
stompClient.connect(
headers, // 参数
function(frame) {//链接Web Socket的服务端。 connectCallback
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/queue/119656321610240/message', function(respnose){ //订阅/topic/getResponse 目标发送的消息。这个是在控制器的@SendTo中定义的。
console.log('message: ' + JSON.parse(respnose.body));
showResponse(JSON.parse(respnose.body));
});
}
);
}
我已经阅读了spring文档,它说需要添加CORS配置,而我做到了:
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
// 客户端与服务器端建立连接的点
stompEndpointRegistry.addEndpoint("/endpointWisely")
.setAllowedOrigins("*")
//.setHandshakeHandler(createMyHandShakeHandler())
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
messageBrokerRegistry.enableSimpleBroker("/queue", "/topic");
messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
// registry.setUserDestinationPrefix("/user/");
}
我做了所有这些,但是仍然出现错误405。 需要帮忙!谢谢!