ESP32 WebServer Library – hasArg()

Home / References / ESP32 Library / WebServer Library

Description

The hasArg() method is a member function of the ESP32 WebServer class. Its primary purpose is to check whether a specific argument (parameter) exists within the data received from an HTTP client request. This function is crucial for validating input; before attempting to read the value of an argument using methods like arg(), you can use hasArg() to ensure the argument was actually provided by the client. This helps prevent errors and allows your code to handle missing parameters gracefully.

It checks for arguments passed via GET (in the URL query string) or POST (in the request body, typically from form submissions).


Syntax and Usage

To check for the presence of a specific argument, call the hasArg() method on your WebServer object instance, passing the name of the argument you are searching for.

#include <WebServer.h>

// Assuming 'server' is your WebServer object instance
// WebServer server(80);

void handleControl() {
  String argToCheck = "command"; // Name of the argument we expect

  // Check if the argument named "command" exists
  if (server.hasArg(argToCheck)) {
    // Yes, it exists. We can now safely get its value.
    String commandValue = server.arg(argToCheck);
    Serial.print("Received command: ");
    Serial.println(commandValue);
    // ... process the command ...
  } else {
    // No, the argument named "command" was not sent.
    Serial.println("No 'command' argument received.");
    // ... handle the case where the command is missing ...
  }
}

Usage:

  • yourServerObject.hasArg(argumentName): Call this method on your active WebServer instance (e.g., server), providing the name of the argument (as a String or const char*) you wish to check for. It returns true if an argument with that specific name was found in the current request, and false otherwise.

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)

This method requires one argument:

  • name: The specific name of the HTTP request argument (parameter) you want to verify the existence of. This argument should be passed as a String object or a compatible type like a C-style string literal (const char*). Note that the name matching is case-sensitive. For example, hasArg("Value") will return false if the received argument was named "value".

Return Value

The hasArg() method returns a boolean value indicating the presence or absence of the specified argument:

  • Return Type: bool.
  • Value:
    • true: Returned if an argument exactly matching the provided name exists in the collection of arguments parsed from the current HTTP request.
    • false: Returned if no argument with the specified name was found in the request.

Example Codes

This example demonstrates how to use the hasArg() method to control the ESP32’s built-in LED (usually on GPIO 2). The server listens for requests on the /led path. It specifically checks if an argument named “state” was included in the request using server.hasArg("state"). If the “state” argument exists, it reads its value; if the value is “on”, the LED turns on, and if it’s “off”, the LED turns off. If the “state” argument is missing entirely, a message indicating this is sent back to the client and printed to the Serial Monitor.

To test this code:

  1. Upload the sketch to your ESP32 after replacing the placeholder Wi-Fi credentials.
  2. Open the Serial Monitor to view the ESP32’s IP address after it connects.
  3. Open a web browser on a device on the same network.
  4. To turn the LED on, navigate to: http://<ESP32_IP>/led?state=on
  5. To turn the LED off, navigate to: http://<ESP32_IP>/led?state=off
  6. To see the handling for a missing argument, navigate to just: http://<ESP32_IP>/led
  7. Observe the ESP32’s built-in LED and the messages printed on the Serial Monitor and displayed in the browser.
/*
 * Author: Avant Maker
 * Date: April 21, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * hasArg() method to control the ESP32's built-in LED
 * (usually on GPIO 2). 
 *
 * 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>

// Replace with your network credentials
const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

// Define the GPIO for the built-in LED (usually GPIO 2 on many ESP32 boards)
#ifndef LED_BUILTIN
#define LED_BUILTIN 2
#endif

// Create WebServer object on port 80
WebServer server(80);

// Function to handle requests to /led
void handleLedControl() {
  String responseMessage;
  bool ledStateChanged = false;

  // Check specifically for the 'state' argument
  if (server.hasArg("state")) {
    String ledStateValue = server.arg("state"); // Get the value if it exists
    Serial.print("Received /led request with state argument: ");
    Serial.println(ledStateValue);

    if (ledStateValue == "on") {
      digitalWrite(LED_BUILTIN, HIGH); // Turn LED ON
      responseMessage = "LED is now ON.";
      ledStateChanged = true;
    } else if (ledStateValue == "off") {
      digitalWrite(LED_BUILTIN, LOW); // Turn LED OFF
      responseMessage = "LED is now OFF.";
      ledStateChanged = true;
    } else {
      responseMessage = "Invalid value for 'state' argument. Use 'on' or 'off'.";
    }
  } else {
    // The 'state' argument was not provided
    Serial.println("Received /led request without 'state' argument.");
    responseMessage = "Missing 'state' argument. Use ?state=on or ?state=off.";
  }

  // Send response back to the client
  server.send(200, "text/plain", responseMessage);
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED pin as an output
  digitalWrite(LED_BUILTIN, LOW); // Start with LED off

  Serial.println();
  Serial.println("Starting ESP32 Web Server for LED control...");

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" Connected!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Define request handler for /led path
  server.on("/led", handleLedControl);

  // Start the server
  server.begin();
  Serial.println("HTTP server started. Access /led?state=on or /led?state=off");
}

void loop() {
  // Handle client requests
  server.handleClient();
}

error: Content is protected !!