Spring Cloud Gateway 跨域以及报错解决

本文详细解析了Spring Cloud Gateway的配置方法,特别是如何避免503错误的出现,以及提供了两种解决跨域问题的有效策略:一是通过创建自定义的CorsConfig类,二是直接在application.yml中进行配置。

请求网关转发时,报错503

注意application.yml中,配置routes时:

spring:
  application:
    name: getway-service
  cloud:
    gateway:
      routes:
      - id: pms-route #注意id前面的 - 要与routes对齐,不然调用服务时会出现503错误
        uri: lb://pms-service
        predicates:
          - Path=/pms/**

一定要保证对齐方式正确,不然通过gateway调用服务时,会出现503错误。 

 

跨域问题解决】:

一、配置好gateway之后,创建跨域配置类CorsConfig来实现跨域情况(推荐):

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.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;

@Configuration
public class CorsConfig {

    /**
     * 该访问配置跨域访问执行
     * @return
     */
    @Bean
    public CorsWebFilter  corsWebFilter(){
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        //cors跨域配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);//是否允许携带cookie
        corsConfiguration.addAllowedOrigin("*"); //允许跨域访问的域名,可填写具体域名,*代表允许所有访问
        corsConfiguration.addAllowedMethod("*");//允许访问类型:get  post 等,*代表所有类型
        corsConfiguration.addAllowedHeader("*");

        //配置源对象
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        //cors 过滤器对象  注意!CorsWebFilter不要导错包
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }

}

二、通过配置文件实现:

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

 

 【报错一

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

解决:

在配置类CorsConfig中:

corsConfiguration.addAllowedOrigin("*")   这一项需要填写具体请求者的地址,不能用*来代替。

 

报错二

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

解决:

在配置类CorsConfig中:

corsConfiguration.setAllowCredentials(true);//是否允许携带cookie
corsConfiguration.addAllowedHeader("*");

这两项设置成这样既可。

 

 

 

 

### 解决 Spring Cloud Gateway 配置完成后访问报错 404 的方法 当遇到 Spring Cloud Gateway 访问接口返回 404 错误的情况时,通常是因为路由配置不正确或者路径映射存在问题。以下是详细的排查和解决办法: #### 1. 检查 `servlet.context-path` 设置 如果项目中设置了 `server.servlet.context-path` 属性,则实际的 API 请求路径将会变为 `${context.path}/api`[^1]。因此,在定义网关路由时应考虑此上下文路径的影响。 #### 2. 确认路由 ID 对齐方式 确保在 `application.yml` 文件中的 `routes` 下面定义的每条路由前都有连字符 `-` 并且与其他项保持水平对齐。不对齐可能会引发诸如 503 这样的错误而不是 404,但这也是配置不当的表现之一[^3]。 ```yaml spring: application: name: getway-service cloud: gateway: routes: - id: pms-route # 注意这里的 '-' 符号要与 'routes' 对齐 uri: lb://pms-service predicates: - Path=/pms/** ``` #### 3. 处理多级断言规则顺序 对于具有不同层次结构的服务路由(例如 coupon_route 和 product_route),应该按照从高到低的优先级来排列这些路由。更具体的模式应当位于较早的位置以便先被匹配处理,从而避免因次序问题引起的 404 错误[^5]。 #### 4. 核实 URI 地址准确性 确认所使用的负载均衡器 (`lb`) 后端服务名称是否已在 Nacos 或其他注册中心成功注册并可用。此外还要验证目标微服务的实际 URL 是否拼写无误,并能通过直连方式进行正常通信测试。 #### 5. 排除影响因素 虽然这不是直接引起 404 的原因,但如果存在 CORS (Cross-Origin Resource Sharing) 相关设置不合理的话也可能间接造成前端无法获取资源而显示为 404 页面。可以参照特定版本下的最佳实践调整相应的头信息和其他参数以支持源资源共享需求[^2]。 #### 6. 审视文件上传场景特殊性 如果是涉及到大文件传输或者其他复杂表单提交操作的情况下,请特别留意是否有额外的数据转换逻辑或中间件干扰到了原始 HTTP POST 请求体的内容完整性,进而导致接收方找不到预期的目标处理器函数[^4]。 综上所述,以上几点可以帮助定位并修复由 Spring Cloud Gateway 引起的 404 响应码异常状况。建议逐一审查上述方面直至找到确切的原因所在。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值