如何解决ESP32异步web服务器错误



我在家里忙着做一个项目。我有一个esp32运行异步web服务器,我想用react网页向它发出请求。

当我点击一个按钮来运行这段代码时:

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>
)
}

我得到以下错误:

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

我的ESP32异步web服务器上的代码:

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

我在网上寻找CORS错误,但他们都建议使用server.enableCORS()但是上传时失败了。error: 'class AsyncWebServer' has no member named 'enableCORS'

我找不到任何与CORS和ESP32 AsyncWebservers相关的东西。任何帮助将不胜感激!

编辑1:我还添加了这个:DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");,但它没有工作

您还必须添加以下标题:

DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");

对于cors preflight,你必须在你的notFound方法中添加一个未找到的响应,就像这样

if (request->method() == HTTP_OPTIONS) {
request->send(200);
} else {
request->send(404, "application/json", "{"message":"Not found"}");
}

通过在react中使用此代码来解决。

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

我真的不需要比这更高级的东西来完成我的任务

最新更新