vue-cli调用本地 java(springBoot)后端出现跨域问题

在使用vue-cli开发项目时,在本地调试程序时前端接收不到后端返回数据,并报错:

Access to XMLHttpRequest at 'http://localhost:8081/activity/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
createError.js?16d0:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js?16d0:16)
    at XMLHttpRequest.handleError (xhr.js?ec6c:87)

解决办法,在后端配置http请求参数:

由于是临时的,所以直接把方法放到了application类里,注意要添加注解“@EnableScheduling”


    /**
     * CORS support
     * @param headers
     * @param methods
     * @param origins
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="management.endpoints.web.cors.enable", havingValue="true")
    public CorsFilter corsFilter(
            @Value("${management.endpoints.web.cors.allowed-headers}") String headers,
            @Value("${management.endpoints.web.cors.allowed-methods}") String methods,
            @Value("${management.endpoints.web.cors.allowed-origins}") String origins) {
        
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedHeaders(Arrays.asList(headers.split(",")));
        config.setAllowedMethods(Arrays.asList(methods.split(",")));
        config.setAllowedOrigins(Arrays.asList(origins.split(",")));
        config.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
        
    }

application.yml

management:
  endpoints:
    web:
      cors:
        enable: 'true'
        allowed-headers: '*'
        allowed-methods: '*'
        allowed-origins: http://localhost:8080

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值