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

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

html 复制代码
<!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的配置文件如下

java 复制代码
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

相关推荐
KubeSphere 云原生21 小时前
云原生周刊:探索 Gateway API v1.3.0
云原生·gateway
曼彻斯特的海边2 天前
spring-cloud-alibaba-sentinel-gateway
gateway·sentinel·springcloud
xujinwei_gingko4 天前
网关Gateway
微服务·gateway
徐子童4 天前
《Spring Cloud Gateway 快速入门:从路由到自定义 Filter 的完整教程》
java·开发语言·spring cloud·nacos·gateway
亚林瓜子4 天前
AWS API Gateway 配置WAF(中国区)
云计算·gateway·aws·waf
枫super8 天前
Spring Cloud 详解:2025 最新技术与最佳实践
后端·spring·spring cloud·eureka·nacos·gateway·openfeign
cainiao08060510 天前
Gateway全局过滤器:接口耗时统计与黑白名单配置
gateway
亚林瓜子13 天前
AWS中国区中API Gateway中403的AccessDeniedException问题
云计算·gateway·api·aws
blammmp15 天前
Spring Cloud:Gateway(统一服务入口)
spring·spring cloud·gateway
Nerd Nirvana15 天前
网关GateWay——连接不同网络的关键设备
网络·mqtt·计算机网络·gateway·路由器·modbus·电力设备