如何解决Angular Websocket CORS 问题
我正在关注这篇文章并收到 CORS 错误
我创建了一个服务并在一个组件中使用它。 来源:https://grokonez.com/angular-11-springboot-websocket
import { Injectable } from '@angular/core';
import * as Stomp from '@stomp/stompjs';
import * as SockJS from 'sockjs-client';
@Injectable({
providedIn: 'root'
})
export class SocketClientService {
private stompClient = null;
title = 'grokonez';
description = 'Angular-WebSocket Demo';
greetings: string[] = [];
disabled = true;
name: string;
constructor() { }
setConnected(connected: boolean) {
this.disabled = !connected;
if (connected) {
this.greetings = [];
}
}
connect() {
const socket = new SockJS('http://localhost:2023/pipeline');
this.stompClient = Stomp.over(socket);
const _this = this;
this.stompClient.connect({},function (frame) {
_this.setConnected(true);
console.log('Connected: ' + frame);
_this.stompClient.subscribe('/topic/messages',function (hello) {
_this.showGreeting(JSON.parse(hello.body).greeting);
});
});
}
disconnect() {
if (this.stompClient != null) {
this.stompClient.disconnect();
}
this.setConnected(false);
console.log('Disconnected!');
}
sendName() {
this.stompClient.send(
'/app/complaint',{},"hello socket"
);
}
showGreeting(message) {
this.greetings.push(message);
}
}
错误: GET 调用 http://localhost:2023/pipeline/info?t=1618431881710
跨域请求被阻止:同源策略不允许读取 远程资源在 ‘http://localhost:2023/pipeline/info?t=1618431881710’。 (原因: 如果 CORS 标头,则不支持凭据 ‘Access-Control-Allow-Origin’是‘*’。
我假设这是客户端错误。
来自 Spring 的片段。我认为这已经足够了,否则我会添加更多代码
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/pipeline")
.setAllowedOrigins("http://localhost:4200")
.withSockJS();
}
编辑:当我删除 setAllowedOrigins 时,我看到 DefaultSockJsService.checkOrigin - Origin 标头值 'http://localhost:4200' not allowed.
registry.addEndpoint("/pipeline").withSockJS();
所以看起来问题出在 Angular
关于如何解决 CORS 问题的任何指示?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。