This is my simple attempt to create a WebSocket channel between a JavaScript client and a Java server.
// java websocket server configuration with spring boot
// server port: 8080 set in the "application.yml"
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app")
.enableSimpleBroker("/notification");
}
}
// js websocket client configuration with "webstomp-client"
import webstomp from 'webstomp-client';
const connection = new WebSocket('ws://localhost:8080/websocket');
const stompClient = webstomp.over(connection);
stompClient.connect(()=>{
stompClient.subscribe('/app/notification', () => console.log('Connection established with server'));
});
The console shows the following:
WebSocket connection to 'ws://localhost:8080/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200
I looked at a lot of other posts, and most of them had to do with allowing the origin. I have tried setting the origin to localhost as well as the local IP address, but without success.
What am I missing? Any help would be tremendous.
Edit: The client is created with create-react-app, if that's relevant.
Edit: The client is on: http:localhost:3000, the server is on: http:localhost:8080.
app/notificationin your server?app/notification?localhost:4200and the server onlocalhost:8080for instance. The last thing I could mention is maybe to remove the.setAllowedOrigins("*")and to set the CORS at a global level of your application