calling kubernetes api directly from react app errors with CORS exception

3/6/2020

I spun up a "create react app" instance locally (localhost:3000). I added a button component that call k8s api's get pods command. using local docker-desktop k8s cluster and a proxy (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>);
  }

and the getPods function :

   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
}

when I tried to use my react-app from the browser (run npm start) I got the following error::

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.

is there something I can do to disable the CORS?

-- Lior Baber
cors
docker-desktop
kubernetes
kubernetes-apiserver
reactjs

1 Answer

3/6/2020

Option 1: try installing a chrome plugin such as allow-cors-access-control (this is likely a dev-mode only issue with chrome)

Option 2: setting up a custom route in your api (assuming you have one) which makes the call for you, and then call your own route from the site

(there are probably other options as well that other people may suggest, but these are a decent starting point)

-- Bill Metcalf
Source: StackOverflow