We are arguing 404 Error with WebSocket + StompJS first connect on "info" section.
Based on Next.js,JavaSpring with StompJS, SockJS, Websocket, We try to make real time chatting website.
But the first check "info" was returned 404 Error. I learend that SockJS Client request "GET/Info" to get Server's basic info. and then when Server supportWebSocket, Server response 200 response with isCookies needed or CORS Origin info . After that we could connect and subscribe to Websocket.
below pic is the Network/. enter image description here
Why we event can't connect to the server for first check??
** FE code PS. We are using Proxy on NExt.js
useEffect(() => {
const socket = new SockJS('/ws', null, {transports: ["websocket", "xhr-streaming", "xhr-polling"]});
const client = new Stomp.Client({
webSocketFactory: () => socket,
debug: (str) => {
console.log(`debg: ${str}`)
},
onConnect: () => {
console.log("=== connect Success === ");
},
onStompError: (frame) => {
console.error('Broker reported error: ' + frame.headers['message']);
console.error('Additional details: ' + frame.body);
},
});
client.activate();
return () => {client.deactivate();}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
//Proxy setting : next.config.js
const nextConfig = {
async rewrites(){
return {
beforeFiles: [
{
source:"/ws/:path",
destination: "https://server.farmingsoon.site/ws/:path",
}
]
}
},
....
** BE Code
- WebsocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/sub");
registry.setApplicationDestinationPrefixes("/pub");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOriginPatterns("https://farmingsoon.vercel.app", "http://localhost:3000")
.withSockJS();
}
}
- WebConfig.
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final AuthenticationInterceptor authenticationInterceptor;
private final List<String> excludePointList = Arrays.asList();
private final List<String> addEndPointList = Arrays.asList("/api/**");
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS" , "PATCH")
.exposedHeaders("accessToken", "refreshToken");
}
};
}
Please give us advice.
We try to change the WebSocketConfig from
etAllowedOrigins("*")
to
.setAllowedOriginPatterns("https://farmingsoon.vercel.app", "http://localhost:3000")
.withSockJS();
.