gpt4 book ai didi

nodemcu esp8266 中的 CORS 问题

转载 作者:行者123 更新时间:2023-12-04 14:34:23 33 4
gpt4 key购买 nike

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.100.2:8100' is therefore not allowed access. The response had HTTP status code 404.



我在尝试在物联网 ESP8266 网络服务器中调用 put/post 请求时遇到上述错误。

为了解决这个问题,我尝试添加以下代码。但没有任何效果。
server.on("/", HTTP_OPTIONS, []() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Allow", "HEAD,GET,PUT,POST,DELETE,OPTIONS");
server.sendHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT");
server.sendHeader("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept");
});

server.on("/testPost", HTTP_POST, testCors);
server.on("/testPut", HTTP_PUT, testCors);

在函数内部
void testCors()
{
Serial.print("HTTP Method: ");
Serial.println(server.method());

server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Allow", "HEAD,GET,PUT,POST,DELETE,OPTIONS");
server.sendHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT");
server.sendHeader("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept");
server.send(200, "text/plain", "");
}

感谢

最佳答案

这是对我有用的通配符路径的解决方案

void config_rest_server_routing()
{
server.on("/", HTTP_GET, []() {
server.send(200, "text/html",
"Welcome to the ESP8266 REST Web Server");
});
server.on("/leds", HTTP_GET, get_leds);
server.on("/leds", HTTP_POST, testCors);
server.on("/leds", HTTP_PUT, testCors);

server.onNotFound(handleNotFound);
}
void handleNotFound()
{
if (server.method() == HTTP_OPTIONS)
{
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Max-Age", "10000");
server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
server.sendHeader("Access-Control-Allow-Headers", "*");
server.send(204);
}
else
{
server.send(404, "text/plain", "");
}
}

关于nodemcu esp8266 中的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161837/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com