'How do i solve ESP32 async webserver cors error

I am busy making a project at home with fastled. I have an esp32 running an async webserver and I want to make requests to it with a react webpage.

When I click a button to run this code:

function EffectBasic () {

     function handleChangeEffect() {
         var xhttp = new XMLHttpRequest();
         xhttp.open("GET", "http://192.168.0.165/Rainbow", true);
         xhttp.setRequestHeader('Access-Control-Allow-Headers', '*');
         xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
         xhttp.send();
    }

    return(
        <div>
            <h1> Police </h1>
            <button onClick={handleChangeEffect()}>BTN</button>
        </div>
    )
}

I get the following error:

Access to XMLHttpRequest at 'http://192.168.0.165/Rainbow' 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.

GET http://192.168.0.165/Rainbow net::ERR_FAILED

Access to XMLHttpRequest at 'http://192.168.0.165/Rainbow' 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.

GET http://192.168.0.165/Rainbow net::ERR_FAILED

the code on my ESP32 ASYNC webserver:

 server.on("/Rainbow", HTTP_GET, [](AsyncWebServerRequest *request){
        changeShow("Rainbow");
        request->send(200, "text/plain", "Rainbow");
    });

I looked online for the CORS error but all of them suggest using server.enableCORS() but it fails when getting uploaded. error: 'class AsyncWebServer' has no member named 'enableCORS'

And I can't find anything related to CORS and ESP32 AsyncWebservers. Any help would be appreciated!

EDIT 1 : I also added this: DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); but it didn't work



Solution 1:[1]

Solved it by using this code in react instead.

const handleChangeEffect = async() => {
         //fetch('http://192.168.0.165/Rainbow');
         const data = await axios.get('http://192.168.0.165/Rainbow')
         console.log(data)
        }

I don't really need anything more advanced then this to complete my task

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Duarte Somsen