【发布时间】:2020-06-15 00:32:05
【问题描述】:
我正在尝试寻找如何通过 WebSocket 连接 VueJs 和 Spring 的解决方案。
WebSocket 配置(春季)
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket")
.setAllowedOrigins("http://localhost:8080")
.withSockJS();
}
我尝试了几个使用 .setAllowedOrigins("") 的选项,例如“*”、“http://localhost:8080”,或者不要使用它。
我的项目中也有 CORS conf。
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
在我的 CORS conf 中,我尝试了很多选项,但没有结果:(
最后是客户端连接(VueJs):
connect() {
this.socket = new SockJS("http://localhost:8081/gs-guide-websocket");
this.stompClient = Stomp.over(this.socket);
this.stompClient.connect(
{},
frame => {
this.connected = true;
console.log(frame);
this.stompClient.subscribe("/topic/chat/1", tick => {
console.log(tick);
this.received_messages.push(JSON.parse(tick.body).content);
});
},
error => {
console.log(error);
this.connected = false;
}
);
}
在我尝试过的所有事情上,我都收到了这个错误:
从源 'http://localhost:8080' 访问 XMLHttpRequest 在 'http://localhost:8080' 已被 CORS 策略阻止:响应中的 'Access-Control-Allow-Credentials' 标头的值是 '' 必须是 '当请求的凭据模式为“包含”时,为 true。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
有什么解决方案可以让它发挥作用吗?
仅供参考:
-
春天:
localhost:8081 -
VueJs:
localhost:8080
感谢大家的帮助:)
【问题讨论】: