对预检请求的响应未通过访问控制检查:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。因此,不允许原点“ http://192.168.100.2:8100” 访问。响应的HTTP状态代码为404。
尝试在物联网ESP8266 Web服务器中调用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", "");
}
谢谢
答案 0 :(得分:1)
这是适用于我的通配符路径的解决方案
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", "");
}
}
答案 1 :(得分:-1)
只需在每个响应之前添加以下行:
server.sendHeader("Access-Control-Allow-Origin", "*");