网关以及跨域问题踩坑

一.网关:

1.pom

     <dependency>
            <groupId>com.cxb</groupId>
            <artifactId>xmall_common</artifactId>
            <version>1.0-SNAPSHOT</version>
<!--            //要排除掉spring-boot-starter-web 不然启动报错-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

2.网关配置

spring:
  cloud:
    gateway:
      routes:
        - id: goods_route
          uri: lb://xmall-goods
#          监听的访问路径
          predicates:
            - Path=/api/goods/**
#          转发的路径
          filters:
#          重写的路径,把/api/... 转为 /.......
#          如:http://localhost:88/api/goods/brand/findAll 转  http://localhost:9004/goods/brand/findAll
            - RewritePath=/api/(?<segment>.*),/$\{segment}

3.配置跨域,

package com.qingcheng.gateway.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() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //1、配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsWebFilter(source);
    }
}

附:记得如果这里配置好跨域了,controller就不用配置@CrossOrgin 了,不然会出现以下错误

The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed.

 

 

另外记得,在写前端api 路径时记得加上http,不然会报以下错误

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension

 

posted @ 2021-03-26 17:24  呆马and鸽子  阅读(471)  评论(0)    收藏  举报