How to troubleshoot and resolve 404 on SockJs's /info path when with cross-origin

≯℡__Kan透↙ 提交于 2019-12-23 04:42:54

问题


I'm having trouble with SockJs and CORS. I use spring. I set up the WebMvcConfigured as follows:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry
                    .addMapping("/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowCredentials(true);
            ;
        }
    };
}

and WebSocketConfig as follows:

    @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic");
    config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry
            .addEndpoint("/gs-guide-websocket")
            .setAllowedOrigins("*")
            .withSockJS();
}

However, when my web client tries to GET against /gs-guide-websocket/info , it gets a 404.

SockJs's specification requires a /info path to be present. It seems like even though I did use .withSockJS() on the server side, it did not set up the /gs-guide-websocket/info path.

How should I create this path through spring and/or spring-websocket?

Thank you,

Kevin


回答1:


I am not using the STOMP protocol, whereas I have configured the websocket with SockJS which is working fine for me.

Here the message payload has sent as response to the frontend.

CustomWebSocketHandler.java

@Component
public class CustomWebSocketHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("message", "Session started");
        jsonObject.addProperty("payload", payload);
        session.sendMessage(new TextMessage(new Gson().toJson(jsonObject)));
    }   
}

WebSocketConfig.java

@EnableWebSocket
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private CustomWebSocketHandler customWebSocketHandler;

    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {

        webSocketHandlerRegistry
            .addHandler(customWebSocketHandler, "/socket")
            .setAllowedOrigins("*")
            .withSockJS()
            .setHeartbeatTime(20);      
    }
}


来源:https://stackoverflow.com/questions/56336155/how-to-troubleshoot-and-resolve-404-on-sockjss-info-path-when-with-cross-origi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!