我正在尝试构建一个聊天应用程序。在VPS上托管时,我收到来自浏览器的错误消息
Access to XMLHttpRequest at 'http://localhost:8080/samplews/info?t=1603709911491' from origin 'http://my-server-ip:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我的WebSocketConfiguration类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/samplews").setAllowedOrigins("http://my-server-ip:8081").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry){
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
我还尝试添加一个WebMvcConfiguration,它不会更改任何内容:
@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://my-server-ip:8081")
.allowedMethods("GET");
}
我正在使用springboot版本2.2.1.RELEASE,并且尝试使用最新版本。
客户端是一个棱角分明的应用程序,除此以外什么都不做:
ngOnInit() {
const ws = new SockJS(this.webSocketEndPoint);
this.stompClient = Stomp.over(ws);
this.stompClient.connect({}, (frame) => {
// TODO: Do somenthing when connecting ws
console.log(frame);
});
}
客户端和服务器位于两个不同的docker容器上,这是docker ps的结果:
f3aa46625fc4 chatapp "java -jar /app.jar" 15 minutes ago Up 15 minutes 0.0.0.0:8080->8080/tcp chatapp
7aa6e8a885de chatui "catalina.sh run" 16 minutes ago Up 16 minutes 0.0.0.0:8081->8080/tcp chatui
在本地一切正常(即使我使用docker或ng服务客户端并通过IntelliJ启动springboot服务器应用)
我不认为我缺少基本信息,有什么想法吗?
编辑:
我已经更改了
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer
对此:
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer
现在我收到此错误:
GET http://localhost:8080/samplews/info?t=1603798741148 net::ERR_CONNECTION_REFUSED
编辑:
我使用localhost作为打开套接字的url目标,我应该改用服务器ip来解决