7

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!

7
  • developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    – Majenko
    Commented Dec 3, 2018 at 17:26
  • Thanx @Majenko but that is too general and doesn't address the esp8266 scenario.
    – Chiwda
    Commented Dec 3, 2018 at 17:46
  • 1
    add the CORS header to every response, not only for 'preflight' OPTIONS request. @Majenko, only resources ncluded from other server need CORS headers
    – Juraj
    Commented Dec 3, 2018 at 18:27
  • 1
    you don't need the OPTIONS support, just add the ACAO header to the response
    – dandavis
    Commented Dec 3, 2018 at 20:12
  • 1
    @Juraj and @ dandavis I combined both your comments and it now works! I removed the OPTIONS part and put server.sendHeader("Access-Control-Allow-Origin","*"); in the response. Thanx! If either want to put it in the form of an answer I will be happy to accept it.
    – Chiwda
    Commented Dec 3, 2018 at 23:01

3 Answers 3

10

Add the CORS header to every response, not only for 'preflight' OPTIONS request. The OPTIONS support is optional, but the response returning the 'shared resource' must contain the CORS header

"Access-Control-Allow-Origin: *"

EDIT: since 2020, the library has server.enableCORS(true);

4

just add this line before every response:

server.sendHeader("Access-Control-Allow-Origin", "*");

4
server.enableCORS(true);

The server will add the response Access-Control-Allow-Origin=* header

1
  • enableCORS was added in 2020
    – Juraj
    Commented Jan 14, 2022 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.