Spring和React的websocket聊天也没有工作,因为CORS



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

我正在尝试使用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

非常感谢您的帮助!

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

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

相关内容

最新更新