【问题标题】:Spring and React websocket chat nor working because of CORS由于 CORS,Spring 和 React websocket 聊天无法正常工作
【发布时间】:2023-03-08 07:07:01
【问题描述】:

可能这是一个愚蠢的问题,但我不知道如何处理它。

我正在尝试使用 Spring 作为后端和 React 作为前端创建聊天,然后将后端部署到 Heroku

问题是应用无法建立连接,因为 CORS 出现错误

Access to XMLHttpRequest at 'https://inversedevs.herokuapp.com/ws/info?t=1606041704061' from origin 'http://localhost:3000/' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. GET https://inversedevs.herokuapp.com/ws/info?t=1606041723180 net::ERR_FAILED

我的 SockJS 客户端是这样的

<SockJsClient
          url={SOCKET_URL}
          topics={['/topic/user']}
          onConnect={this.onConnected}
          onDisconnect={console.log("Disconnected!")}
          onMessage={msg => this.onMessageReceived(msg)}
          debug={false}
        />

我的 Java 代码是用于控制器的:

@Controller
public class SocketController {

@MessageMapping("/user-all")
@SendTo("/topic/user")
public MessageBean send(@Payload MessageBean message) {
    return message;
}

}

用于 WebMvcConfigurer 实现

    @Override
public void addCorsMappings(CorsRegistry registry) {
   registry.addMapping("/**").allowCredentials(true).allowedOrigins("*").allowedMethods("*");
}

对于 WebSocketMessageBrokerConfigurer 的实现

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
    stompEndpointRegistry.addEndpoint("/websocket-chat")
            .setAllowedOrigins("*")
            .withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic/");
    registry.setApplicationDestinationPrefixes("/app");
}

}

日志显示握手返回状态为 200

不胜感激!

【问题讨论】:

    标签: reactjs spring heroku cors


    【解决方案1】:

    正如错误消息所述,您不能使用带有通配符来源的凭证模式。您必须禁用凭证模式或在您的原始接受标头中设置特定来源。

    如果您决定保留凭据并设置具体来源,您可能还必须在来源标头处指定正确的端口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多