Home / References / ESP32 Library / WebServer Library
Description
The on()
method in the ESP32 WebServer Library is used to register a handler function that responds to specific HTTP requests made to the ESP32 web server. By associating a URL path (URI) and an HTTP method (e.g., GET, POST) with a callback function, this method enables you to define how the server processes incoming requests. It’s a fundamental building block for creating interactive web applications with the ESP32.
Syntax and Usage
The on()
method can be used in multiple ways depending on your needs. Below are the different syntaxes available, each with a brief description:
– Basic Usage with URI and Handler:
server.on(uri, fn);
Associates a URI with a handler function that responds to all HTTP methods.
– Usage with URI, HTTP Method, and Handler:
server.on(uri, method, fn);
Specifies a URI and an HTTP method (e.g., GET, POST) to trigger a handler function.
– Usage with URI, HTTP Method, Handler, and Upload Handler:
server.on(uri, method, fn, ufn);
Adds support for handling file uploads alongside the standard handler for a specific URI and HTTP method.
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.
Argument(s)
The on()
method accepts the following arguments depending on the syntax used:
- uri: A
const Uri &
object or string representing the URL path (e.g.,"/"
or"/data"
) that the server will respond to. - method: An
HTTPMethod
enum value (e.g.,HTTP_GET
,HTTP_POST
) specifying the HTTP method to handle. This argument is optional and used only in the second and third syntaxes. - fn: A
THandlerFunction
(function with no arguments and no return value, i.e.,void fn(void)
) that defines the server’s response to the request. - ufn: A
THandlerFunction
specifically for handling file uploads. This optional argument is used only in the third syntax and is called when a file is uploaded to the specified URI.
Return Value
The on()
method returns a reference to a RequestHandler
object. This reference can be used to manage or modify the handler later, such as removing it with the removeHandler()
method. However, in typical usage, you don’t need to store or manipulate this return value directly.
Example Codes
Below are example codes demonstrating each usage of the on()
method.
Example 1: Basic Usage with URI and Handler
This code shows how to use the ESP32 WebServer Library’s on()
method to set up a basic web server. It demonstrates how to handle requests made to the root URL (“/”) and respond with a simple “Hello, World!” message.
To use this code, first replace the placeholder values for ssid
and password
with your Wi-Fi network credentials. After uploading the code to your ESP32 and connecting it to Wi-Fi, open a web browser and navigate to the ESP32’s IP address, which will be printed in the Serial Monitor.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* on() method to set up a simple web server that responds to any
* request to the root URL ("/") with a "Hello, World!" message.
*
* 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-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "AvantMaker.com ESP32 Web Server Demo");
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected:");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.begin();
}
void loop() {
server.handleClient();
}
Example 2: Usage with URI, HTTP Method, and Handler
This code demonstrates how to use the ESP32 WebServer Library’s on()
method to respond specifically to HTTP GET requests for the “/info” path. This allows you to control which HTTP methods your server responds to, ensuring data is served only when requested appropriately.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. Then, upload the code to your ESP32. Once connected to Wi-Fi, open a web browser and navigate to the ESP32’s IP address, which is printed to the Serial Monitor. You will then see the message “AvantMaker.com ESP32 Web Server Demo Page”.
/*
* Author: Avant Maker
* Date: March 24, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* on() method to respond only to HTTP GET requests to "/info".
* It’s useful when you want to restrict responses to specific
* HTTP methods, such as serving data only on GET requests.
*
* 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-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
void handleInfo() {
server.send(200, "text/plain", "AvantMaker.com ESP32 Web Server Demo Page");
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected:");
Serial.print("Web Server IP: ");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, handleInfo);
server.begin();
}
void loop() {
server.handleClient();
}
Example 3: Usage with URI, HTTP Method, Handler, and Upload Handler
This code demonstrates how to use the ESP32 WebServer Library’s on()
method to implement file uploads to the ESP32’s SPIFFS file system. It creates a web server that allows users to upload files through a simple HTML form, and then saves the uploaded files to the ESP32’s SPIFFS.
To use this code, first replace “YourWiFiName” and “YourWiFiPassword” with your Wi-Fi credentials. Then, upload the code to your ESP32. Once the ESP32 connects to Wi-Fi, open a web browser and navigate to the ESP32’s IP address, which is printed to the Serial Monitor. You will see an upload form. Select a file and click “Upload” to upload the file to your ESP32’s SPIFFS. The uploaded files will be saved in the “/uploads/” directory within SPIFFS.
ESP32-WebFS: Simplifying SPIFFS File Management for Your ESP32 Projects
If you are looking for a tool or need guidance to upload and manage files in the SPIFFS (SPI Flash File System) of your ESP32 microcontroller, please check out our GitHub project, ESP32-WebFS , which simplifies SPIFFS file management for your ESP32 projects. It also serves as a great reference project that you can integrate into your own projects requiring ESP32 SPIFFS management.
ESP32-WebFS can turn your ESP32 microcontroller into a web server that provides a web-based interface to manage the SPIFFS on your ESP32. It enables you to upload, download, delete, and view files stored on your ESP32, making it easy to interact with your ESP32’s file system wirelessly.
For downloads and instructions on how to use this tool, please visit the ESP32-WebFS GitHub repository.
/*
* Author: Avant Maker
* Date: March 24, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* on() method to implement file uploads to the ESP32's SPIFFS file
* system:
*
* 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>
#include <SPIFFS.h>
const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";
WebServer server(80);
File uploadFile;
void setup() {
Serial.begin(115200);
// Initialize SPIFFS
if(!SPIFFS.begin(true)){
Serial.println("An error occurred while mounting SPIFFS");
return;
}
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Route for the root page
server.on("/", HTTP_GET, []() {
String html = "<form method='post' action='/upload' enctype='multipart/form-data'>";
html += "<input type='file' name='upload'>";
html += "<input type='submit' value='Upload'>";
html += "</form>";
server.send(200, "text/html", html);
});
// Route to handle file uploads
server.on("/upload", HTTP_POST,
// This is the completion handler (called after upload finishes)
[]() {
server.send(200, "text/plain", "File uploaded successfully!");
},
// This is the upload handler (called during upload)
handleFileUpload
);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
void handleFileUpload() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
// Start a new upload
String filename = "/uploads/" + upload.filename;
Serial.printf("handleFileUpload Name: %s\n", filename.c_str());
uploadFile = SPIFFS.open(filename, FILE_WRITE);
} else if (upload.status == UPLOAD_FILE_WRITE) {
// Write uploaded file data
if (uploadFile) {
uploadFile.write(upload.buf, upload.currentSize);
}
Serial.printf("handleFileUpload Data: %u\n", upload.currentSize);
} else if (upload.status == UPLOAD_FILE_END) {
// End of upload
if (uploadFile) {
uploadFile.close();
}
Serial.printf("handleFileUpload Size: %u\n", upload.totalSize);
}
}
Example 4 Create a simple web server with different API endpoints
This code demonstrates how to use the ESP32 WebServer Library to create a simple web server with different API endpoints. It utilizes the server.on()
method, which internally registers handlers for specific HTTP methods and URI paths. This example sets up endpoints to provide the server’s status and uptime (/api/status), device information and free heap memory (/api/info), and a basic HTML page on the root path (/). It also includes a handler for undefined routes, returning a 404 error.
To use this code, first replace "your_SSID"
and "your_PASSWORD"
with your Wi-Fi network credentials. After uploading the code to your ESP32 and it connects to Wi-Fi, open a web browser and navigate to the ESP32’s IP address (printed in the Serial Monitor). You can then access the different API endpoints by appending /api/status
or /api/info
to the ESP32’s IP address in the browser’s address bar.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer to
* register custom request handlers for your
* web server.
*
* 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 innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
// API endpoint handlers
void handleStatus() {
server.send(200, "application/json", "{\"status\":\"online\",\"uptime\":\"" + String(millis()/1000) + "\"}");
}
void handleInfo() {
server.send(200, "application/json", "{\"device\":\"ESP32\",\"freeHeap\":" + String(ESP.getFreeHeap()) + "}");
}
void handleNotFound() {
server.send(404, "application/json", "{\"error\":\"Endpoint not found\"}");
}
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to WiFi. IP Address: ");
Serial.println(WiFi.localIP());
// Regular route handler for the root page
server.on("/", HTTP_GET, []() {
server.send(200, "text/html", "<h1>AvantMaker ESP32 Web Server</h1><p>Access http://[ESP32_IP_ADDRESS]/api/info and http://[ESP32_IP_ADDRESS]/api/status for ESP32 info.</p>");
});
// Define API routes directly instead of using custom handler
server.on("/api/status", HTTP_GET, handleStatus);
server.on("/api/info", HTTP_GET, handleInfo);
// Set up 404 handler
server.onNotFound(handleNotFound);
// Start the server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- Server Operation
- Client Hnadling
- Routing and Handlers
- Authentication
- Request Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!