前后端分离进行跨域访问

  官方文档:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

一、前端需更改api接口位置

 

 

 二、GateWay路由需要进行路由配置

spring:
  cloud:
    gateway:
      routes:
        - id: admin_route
          #断言成功访问路径
          uri: lb://renren-fast
          #断言规则
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}

三、跨域配置

package com.he.gulimall.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 GulimallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //1、配置跨域

        //跨域请求暴露的字段
        corsConfiguration.addAllowedHeader("*");
        //支持哪些方法跨域
        corsConfiguration.addAllowedMethod("*");
        //支持哪些来源的请求跨域
        corsConfiguration.addAllowedOrigin("*");
        //跨域请求默认不包含cookie,设置为true可以包含 cookie
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}

 

posted @ 2022-08-03 15:50  Homnay  阅读(36)  评论(0)    收藏  举报