使用Gateway解决跨域问题时配置文件不生效的情况之一

本文讨论了HTML文件通过axios发起AJAX请求时遇到的跨域问题,SpringCloudGateway配置中CORS限制导致与localhost不匹配。解决方法是修改hosts文件将localhost映射到127.0.0.1或调整CORS配置以适应所有URL。

首先html文件只有一个发送ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试</title>
</head>
<body>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    axios.get("http://localhost:10010/user/1?authorize=admin")
    .then(res=> console.log(res.data))
    .catch(err=>console.log(err))
</script>
</html>

而gateway的配置文件如下

spring:
  application:
    name: gateway
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        cors-configurations:
          '[/**]':
            allowedOrigins: 
              - "http://localhost:8090"
              - "http://www.域名.com"
            allowedMethods:
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*" 
            allowCredentials: true
            maxAge: 360000

使用VSCode打开html页面时,发送ajax请求后浏览器控制台打印结果如下 

 显而易见,html发送的请求没有与gateway设置的允许跨域的url地址匹配上,而将配置文件中的localhost修改为127.0.0.1时,再次访问就可以成功响应。

如果想要localhost也可以正常响应的话,需要修改C:\Windows\System32\drivers\etc\hosts文件添加如下信息

127.0.0.1 localhost

### Spring Boot 2.6.13 结合 Spring Cloud Gateway 配置负载均衡不生效解决方案 在 Spring Boot 2.6.13 和 Spring Cloud Gateway 的环境中,如果负载均衡配置不生效,可能是由于以下几个原因导致。以下是详细的排查和解决方法: #### 1. 确保引入了正确的依赖 Spring Cloud Gateway 的负载均衡功能依赖于 `spring-cloud-starter-loadbalancer` 模块。需要确保在项目的 `pom.xml` 文件中正确引入了以下依赖[^3]: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> ``` 如果没有引入该依赖,Spring Cloud Gateway 将无法使用负载均衡功能。 #### 2. 检查服务注册与发现是否正常 Spring Cloud Gateway 的负载均衡功能通常与服务注册与发现(如 Eureka、Consul 等)结合使用。需要确认以下几点: - 已经正确配置了服务注册中心(如 Eureka),并且服务能够成功注册到注册中心。 - 在网关的配置文件中指定了服务名作为目标地址,而不是具体的 IP 地址或端口。例如: ```yaml spring: cloud: gateway: routes: - id: service_route uri: lb://service-name predicates: - Path=/service/** ``` 此处的 `lb://service-name` 表示通过负载均衡访问名为 `service-name` 的服务[^4]。 #### 3. 检查 Spring Cloud 版本兼容性 不同版本的 Spring Cloud 对负载均衡的支持可能存在差异。Spring Boot 2.6.13 通常对应 Spring Cloud 2021.0.x 版本。确保使用的 Spring Cloud 版本支持 Spring Cloud Load Balancer,并且与 Spring Boot 版本兼容。可以参考官方文档中的版本兼容性矩阵[^4]。 #### 4. 启用调试日志以定位问题 为了更好地排查问题,可以在配置文件中启用调试日志,观察请求处理过程中的详细信息: ```yaml logging: level: org.springframework.cloud.gateway: DEBUG org.springframework.cloud.loadbalancer: DEBUG ``` 通过日志可以确认请求是否正确转发到后端服务,以及负载均衡器的行为。 #### 5. 确认负载均衡器是否被正确初始化 可以通过调试或日志输出确认 Spring Cloud Load Balancer 是否被正确初始化。例如,检查 `LoadBalancerClient` 或 `ReactiveLoadBalancer` 是否被注入到 Spring 容器中。如果未正确初始化,可能是由于自动配置类 `GatewayReactiveLoadBalancerClientAutoConfiguration` 未生效[^1]。 #### 6. 示例代码:完整配置 以下是一个完整的 Spring Cloud Gateway 配置示例,包含负载均衡和支持: ```yaml spring: application: name: gateway-service cloud: gateway: routes: - id: service_route uri: lb://service-name predicates: - Path=/service/** filters: - StripPrefix=1 loadbalancer: retry: enabled: true ``` ```java package com.example.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } } ``` --- ### 注意事项 - 如果重启网关服务后仍然返回 `{ "code": 503, "msg": "服务未找到" }`,可能是由于服务未正确注册到注册中心,或者网关配置中的服务名与实际注册的服务名不一致[^1]。 - 确保服务提供者启动能够正确注册到注册中心,并且网关能够从注册中心获取到服务实例列表。 --- ###
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zmbwcx2003

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值