簡體   English   中英

SpringBoot中的Web socket CORS問題

[英]Web socket CORS issue in SpringBoot

我正在努力在 springboot 中實現 web sockets,我按照 spring 在文檔中給出的示例進行操作。 但是我在嘗試從 Js 前端連接到套接字時收到 cors 錯誤。

控制器-

@CrossOrigin
@RestController
public class GreetingController {
    @MessageMapping("/Hello")
    @SendTo("/topic/greetings")
    public  Greeting greeting(HelloMessage message){
        return new Greeting("Hello, "+ HtmlUtils.htmlEscape(message.getName()));
    }
}

Model 班-

@Data
@NoArgsConstructor
@AllArgsConstructor
public class HelloMessage {
    private String name;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Greeting {
    private String message;
}

配置類-

@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");
    }

前端-

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));
        });
    });
}

后端和前端在不同的端口號上工作。 在進行連接請求時,我收到此錯誤 - 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.

我該如何解決這個問題!

您可以將源原點添加到@CrossOrigin注釋中。

@CrossOrigin(origins = {"http://localhost"})

另見Rest 服務 Cors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM