SpringBoot项目解决跨域问题

报错:Access to XMLHttpRequest at 'http://localhost:88/xxx/xxx/xxx' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

微服务项目存在的此问题,各个微服务之间使用网关转发请求及响应数据。所以,只要在网关中写个过滤器,该过滤器拦截所有请求,在此过滤器中响应浏览器的options请求即可。

springboot项目为我们写好了解决跨域问题的filter,代码如下:

package com.wq.getway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class MallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter() {
        //springboot提供的CorsWebFilter接口的实现类
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //配置所有请求头都不拦截
        corsConfiguration.addAllowedHeader("*");
        //配置所有请求方式都不拦截
        corsConfiguration.addAllowedMethod("*");
        //配置所有请求源都不拦截
        corsConfiguration.addAllowedOrigin("*");
        //配置允许cookie
        corsConfiguration.setAllowCredentials(true);

        //配置注册所有路径
        source.registerCorsConfiguration("/**", corsConfiguration);

        //SpringBoot已经提供了web跨域问题过滤器
        return new CorsWebFilter(source);

    }

}

跨域问题详解:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

 

 

你可能感兴趣的:(springboot)