Search code examples
javascriptwebserveriotesp32arduino-ide

How to add CORS-Header to my esp32 webserver


I have the Problem that I cannot fetch() from my created .json because of an Access-Control-Allow-Origin Error. I found out that I have to create some kind of a header, but I have no idea how such a command looks like with my used librarys and which parameters have to be selected. I hope you can help me with the needed addition to this code.

#include <ArduinoJson.h>
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>

#define DHTPIN 13
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

const char *ssid = "XXX";
const char *pwd = "XXX";

StaticJsonDocument<250> jsonDocument;
char buffer[250];

float temperature;
float humidity;

WebServer server(80);

void setup() {
dht.begin();
Serial.begin(9600);
Serial.println(WiFi.localIP());  
Serial.print("Connect to: ");
Serial.println(ssid);
WiFi.begin(ssid, pwd);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
Serial.print("Connected. IP: ");
Serial.println(WiFi.localIP());
setup_routing();
}

void setup_routing(){
  server.on("/sensor", getEnv);
  sendHeader()
  server.begin();
}

void create_json(char *tag, float value, char *unit){
  jsonDocument.clear();
  jsonDocument["type"] = tag;
  jsonDocument["value"] = value;
  jsonDocument["unit"] = unit;
  serializeJson(jsonDocument, buffer);
}

void add_json_object(char *tag, float value, char *unit){
  JsonObject obj = jsonDocument.createNestedObject();
  obj["type"] = tag;
  obj["value"] = value;
  obj["unit"]  = unit;
}

void read_sensor_data(void * parameter) {
     for (;;) {
     temperature = dht.readTemperature();
     humidity = dht.readHumidity();
     }
     delay(2000);  
}

void getEnv() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  jsonDocument.clear();
  add_json_object("temperature", temperature, "°C");
  add_json_object("humidity", humidity, "%");
  
  serializeJson(jsonDocument, buffer);
  server.send(200, "application/json", buffer);
}

void loop() {
server.handleClient();
}

Solution

  • The fact is, you don't need to. The WebServer it self has API to automatically send CORS header. All you need to do is enable it in the setup. See example below:

    void setup_routing(){
      server.enableCORS(); //This is the magic
      server.on("/sensor", getEnv);
      server.begin();
    }
    

    Feel free to comment if this is not working. I'll update my answer later.