vue学习记录(四)——结合springboot的websocket请求跨域问题

本来以为是前端写的有问题,浏览器报错如下:
WebSocket connection to ‘ws://localhost:8088/xxx’ failed…
在这里插入图片描述
然后百度,google各种搜,后面发现后端控制台报错信息。解决了,就连接成功了。

springboot版本 v2.5.0

后端报错:
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value “*”

解决:
.setAllowedOriginPatterns("*").withSockJS()
在这里插入图片描述
新建跨域请求配置类:

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true); //sessionid 多次访问一致

        // 允许访问的客户端域名
        List<String> allowedOriginPatterns = new ArrayList<>();
        allowedOriginPatterns.add("*");
        corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
//  corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

如果出现错误:
sockjs.js?9be2:1606 GET http://xxxxxxxx:8080/sockjs-node/info?t=1583642185049 net::ERR_CONNECTION_TIMED_OUT

在\node_modules\sockjs-client\dist\sockjs.js

注释代码:(ctrl+f搜全文)

// self.xhr.send(payload);

正常后浏览器打印:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值