sometimes when a client makes a websocket request, the front end displays an error as follows:
index.js:9 WebSocket connection to 'ws://127.0.0.1:8080/shop/ws?uid=3224458&sid=826' failed: Error during WebSocket handshake: Unexpected response code: 403
cause:
as of Spring Framework 4.1.5, the default behavior of WebSocket and SockJS is to accept only the same original requests. You can also allow a list of all or specified sources.
resolved:
links that are allowed to be accessed can be set when registered in WebSocketConfig.
setAllowedOrigins(String[] domains) allows long connections to a given domain name or IP(including port number), domains allowed to be accessed.
if you use the “*” sign indefinitely, and if you specify a domain name, you must start with HTTP or HTTPS.
example:
setAllowedOrigins (” http://127.0.0.1:8080 “);
or add setAllowedOrigins(“*”)
@Configuration
@EnableWebMvc
@EnableWebSocket
public class ShopWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
@Resource
private ShopWebSocketHandler shopWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(shopWebSocketHandler, "/ws").addInterceptors(new ShopHandshakeInterceptor()).setAllowedOrigins("*");
registry.addHandler(shopWebSocketHandler, "/sockjs/ws").addInterceptors(new ShopHandshakeInterceptor()).withSockJS();
}
}
div>