k8s ingress 配置跨域

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

猜你喜欢

转载自blog.csdn.net/leafcat7/article/details/132564450
今日推荐