-1

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
  • 852
  • 3
  • 11
  • 25

1 Answers1

0

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
  • 650
  • 4
  • 6
  • option 1 didn't solve the issue, I didn't quite understood what you mean for option 2. can you clarify a bit? – Lior Baber Mar 08 '20 at 06:51
  • Usually cors errors only prevent browser-to-server interactions. If you set up your own route that serves as basically a proxy to kubernetes, it will likely work since now it’s server-to-server. This might be hard to do if you are using CRA since you don’t manage your own server (at least out of the box). But there are plenty of articles that say how to use CRA with a custom express server. – Bill Metcalf Mar 09 '20 at 11:57