我在本地创建了一个“创建反应应用程序”实例(localhost:3000
)。我添加了一个调用 k8s api 的 get pods 命令的按钮组件。使用本地docker-desktop
k8s 集群和代理(kubectl proxy --port=8080
):
import {getPods} from './Api.js'
import React, { Component } from 'react'
export default function Button(props) {
const api = "http://localhost:8080";
const namespace = 'my_namespace';
const respose = async () => {const a= await getPods(api,null,namespace);console.log(a)};
return (<button onClick={respose}>ClickMe</button>);
}
和getPods
功能:
export async function getPods(host, token, namespace) {
const response = await fetch(`${host}/api/v1/namespaces/${namespace}/pods`, {
method: 'get',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'
}
});
console.log(response);
return response
}
当我尝试从浏览器(运行npm start
)使用我的 react-app 时,出现以下错误::
Access to fetch at 'http://localhost:8080/api/v1/namespaces/my-namespace/pods' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我可以做些什么来禁用 CORS 吗?