【发布时间】: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