I am using a Raspberry Pi running Chrome (handling the user interface) and connecting via ajax to an Arduino D1 compatible using the IP address as follows:
$.ajax({
type: "GET",
url: "http://10.1.1.100/myfunc?id=5",
error: function(jqXHR, exception, response) {
console.log(exception, response);
etc...
I recently started getting this error (wonder why it didn't happen for the last two years):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.1.1.100/myfunc?n=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I tried various things including setting the browser (Chrome) to --disable-web-security
and various suggestions, here and here (and many more) but I can't seem to get it to work. Currently, I have:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "Root of WebServer!");
}
void setup() {
IPAddress ip(10.1.1.100);
IPAddress gateway(10.1.1.1);
IPAddress subnet(...);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
// put your setup code here, to run once:
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
server.on("/", handleRoot);
server.on("/myfunc", [](){
String message = "";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
String num = server.arg(0);
server.send(200, "text/plain", message);
});
server.on("/myfunc", HTTP_OPTIONS, []() {
server.sendHeader("Access-Control-Allow-Origin","*")
server.send(204);
});
server.onNotFound(handleNotFound);
server.begin();
}
void loop() {
delay(1000);
...
server.handleClient();
}
void handleNotFound(){
String message = "Error!";
server.send(404, "text/plain", message);
}
So what am I doing wrong? Also, one complication that might crop up later is that the domain from where I am calling this in ajax is https and from what I understand https and http are not compatible with cross-domain requests.
Any help is appreciated!