这个问题已经问了很多遍了,但是我无法在后端使用SockJS和Spring Boot v2.2.0.RELEASE在客户端上使用React来解决我的情况。
请清楚一点,我仅使用Websockets!
org.springframework.boot:spring-boot-starter-websocket
我找到的所有解决方案都适用于旧版本的Spring Boot,或者仅适用于Spring。或仅用于常规网络。
这是我的WebSocketConfig
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("WebSocketConfig.registerWebSocketHandlers");
registry.addHandler(new WebSocketHandler(),"/sockjs").setallowedOrigins("*").withSockJS();
}
}
当我在Spring Boot应用程序中使用示例静态HTML页面+一些Javascript代码时,它可以正常工作(来自相同的:8080域),所以我知道这严格是CORS问题。
当我使用以下代码运行示例React应用程序时:
componentDidmount() {
const url = 'http://localhost:8080/sockjs';
const options = {};
let sockjs = new SockJS(url,/*_reserved*/null,options);
sockjs.onopen = function () {
console.log('sockJS endpoint OPENED OK');
this.setState({ socket: sockjs });
};
}
由于我来自localhost:3000(React开发服务器),因此会记录错误消息:
access to XMLHttpRequest at 'http://localhost:8080/sockjs/info?t=1572983410738' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'access-control-allow-origin' header is present on the requested resource.
除了WebsetConfig中的.setallowedOrigins(“ *”)外,我还需要做其他事情吗?
我怀疑我需要设置其他内容,因为websocket协议以常规连接开始,后来又“升级”为websockets。
---更新--- 我已经得出结论,这与SockJS库有关。当我删除它时,就像这样:
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("WebSocketConfig.registerWebSocketHandlers");
registry.addHandler(myHandler(),"/sockjs").setallowedOrigins("*"); // .withSockJS();;
}
并创建一个不带sockjs的简单websocket客户端,如下所示:
var webSocketURL = null;
webSocketURL = protocol + "://" + hostname + ":" + port + endpoint;
console.log("openWSConnection::Connecting to: " + webSocketURL);
try {
webSocket = new WebSocket(webSocketURL);
webSocket.onopen = function(openEvent) {
console.log("WebSocket OPEN: " + JSON.stringify(openEvent,null,4));
}
然后按预期方式工作。当我更改.setallowedOrigins调用时,我得到正确的结果。当它不匹配时,我得到403,当它匹配时,我可以打开websocket。
现在我需要找出sockJS可以阻止这种情况!