k8s ingress 配置跨域

博客主要围绕ingress添加annotations展开。介绍了常规配置可在ingress的yaml文件或rancher页面进行。当http请求带header且有自定义字段时会报跨域,给出了报错信息,并提供测试代码,解决方法是指定cors-allow-headers,不能用*。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ingress添加annotations

常规配置

在 ingress 的yaml文件中,或者 rancher页面配置


    nginx.ingress.kubernetes.io/cors-allow-headers: '*'
    nginx.ingress.kubernetes.io/cors-allow-methods: '*'
    nginx.ingress.kubernetes.io/cors-allow-origin: '*'
    nginx.ingress.kubernetes.io/enable-cors: 'true'

如果http请求种带header

如果是header有自定义字段,则需要指定cors-allow-headers,否则依然会报跨域。例如加入了mytoken字段

报错信息

Access to fetch at xxx from origin xxx has been blocked by CORS policy: Request header field mytoken is not allowed by Access-Control-Allow-Headers in preflight response.
在这里插入图片描述

测试代码

<!DOCTYPE html>
<html>
<head>
  <title>测试跨域</title>
</head>
<body>
  <button id="testButton">test</button>

  <script>
    document.getElementById("testButton").addEventListener("click", async () => {
      const testData = {
        title: "hi!"
      };

      const response = await fetch("http://localhost:8081/demo/test", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
		  "mytoken": "123"
        },
        body: JSON.stringify(testData),
		//credentials: "include" // Add this line to include credentials
      });

      if (response.ok) {
        const responseData = await response.json();
        console.log("test successful:", responseData);
      } else {
        console.error("test failed");
      }
    });
  </script>
</body>
</html>

解决方法

需要指定cors-allow-headers,不能使用*

nginx.ingress.kubernetes.io/cors-allow-headers: >-
      DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,mytoken
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

乘茶蛙泳

just 4 fun

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

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

打赏作者

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

抵扣说明:

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

余额充值