使用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

相关推荐
不会写DN11 小时前
让 gRPC 服务同时支持 HTTP/JSON 的gRPC-Gateway
http·json·gateway
棒棒的唐2 天前
WSL2用npm安装的openclaw,无法正常使用openclaw gateway start启动服务的问题
前端·npm·gateway
wuyikeer4 天前
Nginx反向代理出现502 Bad Gateway问题的解决方案
运维·nginx·gateway
2501_948114244 天前
AI API Gateway 选型指南:2026 年生产环境下的聚合平台深度对比
人工智能·gateway
心勤则明4 天前
Spring AI Alibaba MCP Gateway:将存量服务转换成 MCP Server
人工智能·spring·gateway
hutengyi5 天前
当遇到 502 错误(Bad Gateway)怎么办
gateway
无名-CODING5 天前
Java 爬虫零基础入门:从 HTTP 到 Jsoup 实战
spring cloud·gateway·sentinel
standovon6 天前
Gateway Timeout504 网关超时的完美解决方法
gateway
无名-CODING6 天前
SpringCloud 网关与熔断:Gateway + Sentinel 快速入门
spring cloud·gateway·sentinel
会飞的大可7 天前
022 API网关设计:Gateway路由、限流与鉴权实战
gateway