Spring Cloud:Gateway配置跨域

参考文档:spring cloud gateway跨域问题 - 简书

前景:

        前后端分离项目

        避免前端使用代理

问题:前端发送了一个options权限验证的http请求,爆403错误,

解决:

由于gateway使用的是webflux,而不是springmvc,所以需要先关闭webflux的cors,再从gateway的filter里边设置cors就行了。

package net.youqu.micro.service.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;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * description:
 *
 * @author wangpeng
 * @date 2019/01/02
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

配置:

spring:
  cloud:
    gateway:
      discovery:
      # 跨域
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedHeaders: "*"
            allowedOrigins: "*"
            allowedMethods:
            - GET
              POST
              DELETE
              PUT
              OPTION

Spring cloud gateway 详解和配置使用(文章较长)_荡漾-CSDN博客

CORS通信 -- JavaScript 标准参考教程(alpha)


版权声明:本文为qq_16946803原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。