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

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

首先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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zmbwcx2003

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

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

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

打赏作者

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

抵扣说明:

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

余额充值