ingressadd annotations
General configuration
In the yaml file of ingress, or rancher page configuration
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'
If the http request has a header
If the header has custom fields, you need to specify cors-allow-headers, otherwise the cross-domain report will still be reported. For example, the mytoken field is added
Error message
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.
test code
<!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>
Solution
Cors-allow-headers needs to be specified, * cannot be used
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