跨域问题.docx

  1. 解决跨域,统一请求一个域名(然后用网关,或nginx根据请求url进行请求转发到真正的服务)

文件在D:\E\学习文档子目录压缩\框架\微服务相关\问题解决\跨域问题.docx

    1. 网关服务中配好路由

spring:

  cloud:

    gateway:

      routes:

        - id: admin_route

          uri: lb://renren-fast

          predicates:

            - Path=/api/**

          filters:

            - RewritePath=/api(?<segment>/?.*), /renren-fast/$\{segment}

    1.  编写,允许跨域加入响应头的代码--filter

--如果跨域请求出现 OPTIONS,OPTIONS产生原因是发送真正请求前,

 *  会发一个预检请求,那么我们可以写一个filter在发预检请求的时候,

 *  添加响应头,允许跨域,这样在真正发请求时就可以跨域了

package com.xiangshuai.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("*");

        corsConfiguration.setAllowCredentials(true);

       

        source.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsWebFilter(source);

    }

}

    1. 如果我们在网关里面的filter已经加好了请求头,那么记得将真正请求的应用的请求头去掉(如果有加的话)

@Configuration

public class CorsConfig implements WebMvcConfigurer {

//    @Override

//    public void addCorsMappings(CorsRegistry registry) {

//        registry.addMapping("/**")

//            .allowedOrigins("*")

//            .allowCredentials(true)

//            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")

//            .maxAge(3600);

//    }

}

2.

2.1

2.1.1

2.1.2

2.2   

2.2.1    

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值