Spring Cloud Gateway与Vue前后端分离跨域问题处理

首先先声明一下我的Spring Cloud Gateway版本,因为不同的版本特性会有一些差异。
在这里插入图片描述

方式1:在application.yml配置文件中添加以下代码内容

参考资料:https://docs.spring.io/spring-cloud-gateway/docs/2.2.10.BUILD-SNAPSHOT/reference/html/#cors-configuration

spring:  
  cloud:
    gateway:
       #  CORS跨域处理
       globalcors:
         cors-configurations:
           #  允许跨域的路径(备注:/**表示所有路径)
           '[/**]':
             #  允许哪些请求源跨域(备注:allowCredentials为true时,allowedOrigins不能设置为“*”,会报错)
             allowedOriginPatterns:
               - "*"
#             allowedOrigins: "*"
             #  是否携带cookie跨域
             allowCredentials: true
             #  允许哪种请求头跨域
             allowedHeaders: "*"
             #  允许哪种方法类型跨域(备注:这里我设置了GET、POST、PUT、DELETE、OPTIONS)
             allowedMethods:
               - GET
               - POST
               - PUT
               - DELETE
               - OPTIONS

方式2、创建XXXCorsConfiguration(XXX你需要定义成自己项目相关的名称)

package com.xxx.gateway.config;

import lombok.extern.slf4j.Slf4j;
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 java.util.ArrayList;
import java.util.List;

/**
 * 个人博客网CORS跨域请求配置
 * @author 匿名用户
 * @email 匿名用户@126.com
 * @date 2021/8/6 23:38
 */
@Slf4j
@Configuration
public class XXXCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //  允许哪些请求源跨域
//        corsConfiguration.addAllowedOrigin("*");
        List<String> allowedOriginPatterns = new ArrayList<>();
        allowedOriginPatterns.add("*");
        corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
        //  允许哪种请求头跨域
        corsConfiguration.addAllowedHeader("*");
        //  允许哪种方法类型跨域 get post delete put,*代表允许所有
        corsConfiguration.addAllowedMethod("*");
        //  是否携带cookie跨域
        corsConfiguration.setAllowCredentials(true);
        //  允许跨域的路径
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(source);
    }
}

这两种方式随便一个都能完美解决跨域问题,不过生产环境参数设置上还是要谨慎一些。记录贴以防自己以后在耽误时间。不做任何回复

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值