WebSocket handshake Unexpected response code 403

有时客户端发出websocket请求时,前端会显示如下报错:

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

原因:

从Spring Framework 4.1.5开始,WebSocket和SockJS的默认行为是仅接受相同的原始请求。也可以允许所有或指定的来源列表。

解决:

在WebSocketConfig中注册时可以设置允许访问的链接.
setAllowedOrigins(String[] domains),允许指定的域名或IP(含端口号)建立长连接,domains允许的域名访问。
如果不限时使用"*"号,如果指定了域名,则必须要以http或https开头。

示例:

setAllowedOrigins(“http://127.0.0.1:8080”);
或者添加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();
	}
}

你可能感兴趣的:(spring)