Home > Blockchain >  CORS error with Spring boot, javascript and web socket
CORS error with Spring boot, javascript and web socket

Time:10-27

I'm working on a little test project with a simple html page (using javascript) as Frontend and a Spring Boot application for my apis as Backend. I use websocket with stomp and sockJS to keep alive my connection between front and back. My problem is the following : when I test my connection with Postman i have no problems but when I call the api from my javascript I have the following error : enter image description here

I tried every solutions I've found on internet and now i'm just stuck

Here is my Spring boot App_controller :

@RestController
@CrossOrigin(origins = "*")
public class App_Controller {

    int id = 0;
    ArrayList<Player> players = new ArrayList<Player>();
    public void addTab(Player p){
       players.add(p);
    }

    @MessageMapping("/batch-socket")
    @SendTo("/topic/messages")
    public String send(String message) throws Exception {
        String time = new SimpleDateFormat("HH:mm").format(new Date());
        return (message   " : "   time);
    }


    @RequestMapping (value = "/error", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public String error(){
        return "erreur";
    }
}

Here is my corsConfiguration :

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry){
                registry.addMapping("/**")
                        .allowCredentials(true)
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .maxAge(3600);

            }
        };
    }
}

Here is my WebSocketConfiguration :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/topic")
                .enableSimpleBroker("/app");
    }

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

And finally here is my function to connect to this WebSocket :

    function connect(){
        var socket = new SockJS("http://localhost:8080/batch-socket");
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame){
            setConnected(true);
            console.log('Connected: '   frame);
            stompClient.subscribe('/topic/messages', function(msgOutput){
                console.log(msgOutput);
            })
        })

    }

I tried to just add the @CrossOrigin(origins="*") and @CrossOrigins(origins="http://localhost:63342") and I test multiple possibilities with my CorsConfig.

Thank you for your help in advance (sorry for my english)

CodePudding user response:

You didn't say how your HTML page with JS is loaded. Is it the same localhost:8080 or maybe local file?
For testing you can tell Chrome to ignore cors restrictions:

chrome --disable-web-security --user-data-dir={some dir}

CodePudding user response:

I think that you don’t need to create the @bean WebMvcConfigurer corsConfigurer, if it is for a simple test. Could you please do a test removing the registration of that bean and change the order of the annotations?

@CrossOrigin(origins = "http://localhost:63342")
@RestController
  • Related