'Web socket CORS issue in SpringBoot
I was working on implementing web sockets in springboot, I followed the example spring has given in there docs. But I am getting cors error while trying to connect to socket from Js frontend.
Controller-
@CrossOrigin
@RestController
public class GreetingController {
@MessageMapping("/Hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message){
return new Greeting("Hello, "+ HtmlUtils.htmlEscape(message.getName()));
}
}
Model classes-
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HelloMessage {
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Greeting {
private String message;
}
configuration class-
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/stomp-endpoint").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry){
registry.enableSimpleBroker("/topics");
registry.setApplicationDestinationPrefixes("/app");
}
Frontend-
function connect() {
var socket = new SockJS('http://localhost:8080//stomp-endpoint');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('http://localhost:8080//topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body));
});
});
}
backend and frontend are working on different port numbers. While making the connect req I am getting this error - Access to XMLHttpRequest at 'http://localhost:8080//stomp-endpoint/info?t=1630575287138' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
How can I resolve this issue !
Solution 1:[1]
You can add the source origin to the @CrossOrigin
annotation.
@CrossOrigin(origins = {"http://localhost"})
See also Rest Service Cors
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rupweb |