我有一个运行在本地主机的SpringBoot服务器,端口为8080, 并且npm(提供React应用程序)在本地主机上的端口为3000。
每当我尝试与spring建立websocket连接时,这将显示在浏览器的控制台上(Firefox Nightly):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/ws/info?t=1522629329791.
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match
‘http://localhost:8080/ws/info’).
我创建了一个WebSocketMessageBrokerConfigurer类,并尝试使用null和http://localhost:3000(以及127.0.0.1)设置setAllowedOrigins:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:3000")
.withSockJS();
}
REST请求正常工作,我甚至在一个简单的节点脚本中连接到了websocket,但在浏览器内我没有成功。这是我在浏览器中连接的方式(与脚本中相同):
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
...
let ws = new SockJS('http://localhost:8080/ws/');
let client = Stomp.over(ws);
client.connect({'some-header': 'some-data'}, (success) => {
//client.subscribe(...
}, (error) => {
console.log(error)
})
有人能帮我吗?提前感谢。