如何停止关闭stomp.js WebSocket的CORS策略?

时间:2019-06-22 03:06:20

标签: reactjs spring-boot stomp

我正在为消息传递应用程序开发React.js前端。我正在尝试为短信聊天组打开套接字,但似乎CORS政策正在阻止这种情况的发生:

WebSocket connection to 'wss://dev-api.chatloop.org/stompEndpoint/733/e1l40zsf/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

和:

Failed to load resource: the server responded with a status of 403 ()

还有:

Access to XMLHttpRequest at 'https://dev-api.chatloop.org/stompEndpoint/733/frazjqye/xhr_streaming?t=1561171328160' from origin 'https://dev-react.chatloop.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

还有:

Access to resource at 'https://dev-api.chatloop.org/stompEndpoint/733/cjcd445t/eventsource' from origin 'https://dev-react.chatloop.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我尝试从http://localhost:3000连接时,也会出现非常类似的错误。

但是尽管如此,我仍然从stomp.umd.js收到一个控制台日志,说该套接字已被打开...有时。

在后端,看起来已将Web套接字配置设置为允许跨域访问正确:

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    public static final String CHAT_DESTINATION = "/chatMessages";
    public static final String INVITES_DESTINATION = "/invites";

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stompEndpoint").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker(CHAT_DESTINATION, INVITES_DESTINATION);
        config.setApplicationDestinationPrefixes("/app");
    }

}

所以我倾向于认为问题出在我的前端:

chatService.js

function connectStompClient(chatId) {
  const socket = new SockJS('https://dev-api.chatloop.org/stompEndpoint');
  const stompClient = Stomp.over(socket);
  stompClient.connect(
    {},
    function() {
      stompClient.subscribe('/chatMessages/newMessage' + chatId, function(message) {
        console.log('inside subscribe success callback');
        showMessage(message);
      });
    },
    function(error) {
      console.log(error.toString());
    }
  );
  function showMessage(message) {
    console.log('message from stompClient: ', message);
  }
}

...,在点击事件中通过此函数调用:

ChatsPage.js

handleShowChat = (chatType, chatId) => {
    const { dispatch, userRole } = this.props;
    this.setState((prevState) => {
      return {
        showChat: !prevState.showChat,
        chatId: chatId
      };
    });
    dispatch(chatsActions.getMessages(chatType, chatId, userRole));
    chatService.connectStompClient(chatId);
  };

有人能看到我需要做些什么才能使这个插座干净地打开吗?

0 个答案:

没有答案