ESP32 WebServer Library – enableCORS()

Home / References / ESP32 Library / WebServer Library

Description

The enableCORS() method is used to enable or disable Cross-Origin Resource Sharing (CORS) support on the ESP32 WebServer. When CORS is enabled, the server automatically adds the necessary HTTP headers to allow web browsers to make cross-origin requests to your ESP32 server from web pages hosted on different domains, ports, or protocols. This method is essential for modern web applications that need to communicate with IoT devices from browser-based interfaces. By default, CORS is disabled for security reasons, but enabling it allows your ESP32 to serve APIs and resources that can be accessed by web applications running on different origins, making it ideal for creating web-based control panels, dashboards, and IoT applications.

Understanding Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is a web security feature implemented by web browsers to control how web pages from one domain can access resources from another domain. For beginners, it’s important to understand that browsers enforce a “same-origin policy” by default, which means a web page can only make requests to the same domain, port, and protocol from which it was served.

For example, if you have a web page served from https://myapp.com and you want it to communicate with your ESP32 server at http://192.168.1.100, the browser will block this request because they have different origins (different protocol, domain, and port). This is where CORS comes in – it allows the server (your ESP32) to explicitly permit such cross-origin requests by including specific HTTP headers in its responses.

When you enable CORS on your ESP32 WebServer, it automatically adds these headers to all responses:

  • Access-Control-Allow-Origin: * – Allows requests from any origin (domain)
  • Access-Control-Allow-Methods: * – Allows all HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Access-Control-Allow-Headers: * – Allows any headers in the request

This makes your ESP32 server accessible to web applications regardless of where they are hosted, which is particularly useful for IoT projects where you want to create web-based control interfaces that can be hosted anywhere.

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.

Syntax and Usage

The enableCORS() method has a simple syntax:

  • Enable CORS: server.enableCORS(true) or server.enableCORS() – Enables CORS support by adding the necessary headers to all responses.
  • Disable CORS: server.enableCORS(false) – Disables CORS support (default behavior).

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.

Arguments

  • value (boolean) – A boolean value that determines whether to enable or disable CORS support. true enables CORS headers, false disables them (default).

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.

Return Value

The enableCORS() method does not return any value (void return type). The method configures the WebServer internally to include or exclude CORS headers in all HTTP responses.

Example Code

IoT Dashboard with CORS-Enabled API Server

This example demonstrates how to create an ESP32 API server with CORS enabled, allowing web applications from any domain to access sensor data and control GPIO pins. The server provides both a local web interface and API endpoints that can be accessed by external web applications.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, access the web interface at http://ESP32_IP/ to see the dashboard. Test CORS functionality by accessing the API endpoints from a different domain using JavaScript fetch requests, such as fetch('http://ESP32_IP/api/sensor').then(r => r.json()).then(console.log). You can also use curl commands like curl -H "Origin: https://example.com" http://ESP32_IP/api/sensor to test CORS headers.

/*
 * Author: Avant Maker
 * Date: June 18, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to create an ESP32 API server with
 * CORS enabled, allowing web applications from any domain to access sensor
 * data and control GPIO pins. The server provides both a local web
 * interface and API endpoints that can be accessed by external web applications.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * After connecting, access the web interface at http://ESP32_IP/ to see
 * the dashboard. Test CORS functionality by accessing the API endpoints
 * from a different domain using JavaScript fetch requests, such as
 * fetch('http://ESP32_IP/api/sensor').then(r => r.json()).then(console.log).
 * You can also use curl commands like
 * curl -H "Origin: https://example.com" http://ESP32_IP/api/sensor
 * to test CORS headers.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their nnovative ideas to life.
 */

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

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

// Sensor simulation variables
float temperature = 23.5;
float humidity = 65.2;
bool ledState = false;
int ledPin = 2;

// CORS status tracking
bool corsEnabled = true;

void handleRoot() {
  String html = "<!DOCTYPE html><html><head><title>AvantMaker ESP32 CORS Dashboard</title>";
  html += "<style>body{font-family:Arial,sans-serif;margin:20px;background:#f0f0f0;}";
  html += ".container{max-width:800px;margin:0 auto;background:white;padding:20px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}";
  html += ".status{padding:10px;margin:10px 0;border-radius:5px;}";
  html += ".enabled{background:#d4edda;color:#155724;border:1px solid #c3e6cb;}";
  html += ".disabled{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb;}";
  html += ".button{background:#007bff;color:white;padding:10px 20px;border:none;border-radius:5px;cursor:pointer;margin:5px;}";
  html += ".button:hover{background:#0056b3;}</style></head><body>";
  
  html += "<div class='container'>";
  html += "<h1>AvantMaker ESP32 IoT Dashboard with CORS</h1>";
  
  // CORS status
  html += "<div class='status " + String(corsEnabled ? "enabled" : "disabled") + "'>";
  html += "<strong>CORS Status:</strong> " + String(corsEnabled ? "ENABLED" : "DISABLED");
  html += "</div>";
  
  // Sensor data
  html += "<h2>Sensor Data</h2>";
  html += "<p><strong>Temperature:</strong> " + String(temperature, 1) + "°C</p>";
  html += "<p><strong>Humidity:</strong> " + String(humidity, 1) + "%</p>";
  html += "<p><strong>LED Status:</strong> " + String(ledState ? "ON" : "OFF") + "</p>";
  
  // Controls
  html += "<h2>Controls</h2>";
  html += "<button class='button' onclick='toggleLed()'>Toggle LED</button>";
  html += "<button class='button' onclick='refreshData()'>Refresh Data</button>";
  
  // CORS controls
  html += "<h2>CORS Configuration</h2>";
  html += "<button class='button' onclick='enableCors()'>Enable CORS</button>";
  html += "<button class='button' onclick='disableCors()'>Disable CORS</button>";
  
  // API endpoints
  html += "<h2>API Endpoints</h2>";
  html += "<ul>";
  html += "<li>GET /api/sensor - Get sensor data</li>";
  html += "<li>POST /api/led - Toggle LED</li>";
  html += "<li>GET /api/status - Get system status</li>";
  html += "<li>POST /api/cors/enable - Enable CORS</li>";
  html += "<li>POST /api/cors/disable - Disable CORS</li>";
  html += "</ul>";
  
  // JavaScript for AJAX calls
  html += "<script>";
  html += "function toggleLed(){fetch('/api/led',{method:'POST'}).then(()=>location.reload());}";
  html += "function refreshData(){location.reload();}";
  html += "function enableCors(){fetch('/api/cors/enable',{method:'POST'}).then(()=>location.reload());}";
  html += "function disableCors(){fetch('/api/cors/disable',{method:'POST'}).then(()=>location.reload());}";
  html += "</script>";
  
  html += "</div></body></html>";
  
  server.send(200, "text/html", html);
}

void handleSensorAPI() {
  // Simulate sensor reading variations
  temperature += random(-10, 11) / 10.0;
  humidity += random(-5, 6) / 10.0;
  
  // Keep values in realistic ranges
  temperature = constrain(temperature, 15.0, 35.0);
  humidity = constrain(humidity, 40.0, 90.0);
  
  String json = "{";
  json += "\"temperature\":" + String(temperature, 1) + ",";
  json += "\"humidity\":" + String(humidity, 1) + ",";
  json += "\"led\":" + String(ledState ? "true" : "false") + ",";
  json += "\"timestamp\":" + String(millis()) + ",";
  json += "\"corsEnabled\":" + String(corsEnabled ? "true" : "false");
  json += "}";
  
  server.send(200, "application/json", json);
}

void handleLedAPI() {
  if (server.method() == HTTP_POST) {
    ledState = !ledState;
    digitalWrite(ledPin, ledState);
    
    String json = "{";
    json += "\"led\":" + String(ledState ? "true" : "false") + ",";
    json += "\"message\":\"LED toggled successfully\"";
    json += "}";
    
    server.send(200, "application/json", json);
  } else {
    server.send(405, "application/json", "{\"error\":\"Method not allowed\"}");
  }
}

void handleStatusAPI() {
  String json = "{";
  json += "\"corsEnabled\":" + String(corsEnabled ? "true" : "false") + ",";
  json += "\"freeHeap\":" + String(ESP.getFreeHeap()) + ",";
  json += "\"uptime\":" + String(millis()) + ",";
  json += "\"wifiSignal\":" + String(WiFi.RSSI()) + ",";
  json += "\"chipModel\":\"" + String(ESP.getChipModel()) + "\",";
  json += "\"cpuFreq\":" + String(ESP.getCpuFreqMHz()) + ",";
  json += "\"flashSize\":" + String(ESP.getFlashChipSize());
  json += "}";
  
  server.send(200, "application/json", json);
}

void handleEnableCORS() {
  corsEnabled = true;
  server.enableCORS(true);
  
  String json = "{";
  json += "\"status\":\"success\",";
  json += "\"message\":\"CORS enabled\",";
  json += "\"corsEnabled\":true";
  json += "}";
  
  server.send(200, "application/json", json);
  Serial.println("CORS enabled - Cross-origin requests now allowed");
}

void handleDisableCORS() {
  corsEnabled = false;
  server.enableCORS(false);
  
  String json = "{";
  json += "\"status\":\"success\",";
  json += "\"message\":\"CORS disabled\",";
  json += "\"corsEnabled\":false";
  json += "}";
  
  server.send(200, "application/json", json);
  Serial.println("CORS disabled - Cross-origin requests blocked");
}

void setup() {
  Serial.begin(115200);
  
  // Initialize LED pin
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Enable CORS by default
  server.enableCORS(true);
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/api/sensor", HTTP_GET, handleSensorAPI);
  server.on("/api/led", HTTP_POST, handleLedAPI);
  server.on("/api/status", HTTP_GET, handleStatusAPI);
  server.on("/api/cors/enable", HTTP_POST, handleEnableCORS);
  server.on("/api/cors/disable", HTTP_POST, handleDisableCORS);
  
  // Handle preflight requests (OPTIONS method)
  server.on("/api/sensor", HTTP_OPTIONS, [](){
    server.send(200, "text/plain", "");
  });
  server.on("/api/led", HTTP_OPTIONS, [](){
    server.send(200, "text/plain", "");
  });
  server.on("/api/status", HTTP_OPTIONS, [](){
    server.send(200, "text/plain", "");
  });
  
  // Start server
  server.begin();
  Serial.println("HTTP server started with CORS enabled");
  Serial.println("API endpoints available for cross-origin requests");
  Serial.println("Test CORS with: curl -H 'Origin: https://example.com' " + WiFi.localIP().toString() + "/api/sensor");
}

void loop() {
  server.handleClient();
  
  // Optional: Print periodic status
  static unsigned long lastPrint = 0;
  if (millis() - lastPrint > 60000) { // Every 60 seconds
    lastPrint = millis();
    Serial.println("Status - CORS: " + String(corsEnabled ? "ON" : "OFF") + 
                   ", Free Heap: " + String(ESP.getFreeHeap()) + 
                   ", WiFi Signal: " + String(WiFi.RSSI()) + " dBm");
  }
}

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

error: Content is protected !!