-1

我在本地创建了一个“创建反应应用程序”实例(localhost:3000)。我添加了一个调用 k8s api 的 get pods 命令的按钮组件。使用本地docker-desktopk8s 集群和代理(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 吗?

4

1 回答 1

0

选项 1:尝试安装 chrome 插件,例如allow-cors-access-control(这可能是 chrome 唯一的开发模式问题)

选项 2:在您的 api 中设置一个自定义路由(假设您有一个),它会为您调用,然后从站点调用您自己的路由

(可能还有其他人可能会建议的其他选项,但这些是一个不错的起点)

于 2020-03-06T20:13:05.400 回答