ESP32 HTTP server: Multiple methods allowed on same route

The objective of this post is to explain how we can allow multiple HTTP methods on the same route of an async HTTP web server running on the ESP32, using the Arduino core. The tests of this tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.

Introduction

The objective of this post is to explain how we can allow multiple HTTP methods on the same route of an async HTTP web server running on the ESP32, using the Arduino core.

In this previous post we saw how we could control the HTTP methods allowed on a route, but we only had the option to allow a specific method per route or all methods.

Nonetheless, for some use cases, it could be useful to allow some methods, but not all (for example, allowing GET and POST requests on a given route but not PUT requests).

As mentioned in the previous tutorial, we control the HTTP methods allowed in a route by passing a specific enumerated value to the on method. That enum is specified here and as can be seen by its values it follows a bit flag pattern.

This means that allowing a specific method corresponds to setting a given bit of a byte to true. In the case of the HTTP_ANY value, all the bits are set to 1, which is a good indicator that we can actually mix different methods by setting their bits to 1. We will test this in our code.

The tests of this tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.

If you prefer a video tutorial, please check below my YouTube channel.

The code

The first part of the code follows the pattern we have been using in previous tutorials. We start by the includes, followed by declaring the credentials of the WiFi network as global variables. We will also need an object of class AsyncWebServer, which will also be stored on a global variable.

#include "WiFi.h"
#include "ESPAsyncWebServer.h"

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";

AsyncWebServer server(80);

In the Arduino setup, we open, a serial connection and then we call the functions needed to connect the ESP32 to the wireless network.

Serial.begin(115200);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
}

Serial.println(WiFi.localIP());

Now we will handle the route configuration by calling the on method on the server object. We will call this route “/test”.

We will configure our route to accept both HTTP GET and POST requests. Thus, as second argument of the on method, we need to pass a byte with the corresponding bit flags of these methods set to 1 and the remaining to 0.

We can set the final value using the bitwise OR operator “|” between the enum values for the GET and POST requests.

As response, we will return a simple “ok” message to the client.

server.on("/test", HTTP_POST | HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", "ok");
});

To finalize, we need to call the begin method on the server object so it starts listening to incoming requests. The final source code is shown below.

#include "WiFi.h"
#include "ESPAsyncWebServer.h"

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";

AsyncWebServer server(80);

void setup(){
  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println(WiFi.localIP());

  server.on("/test", HTTP_POST | HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", "ok");
  });

  server.begin();
}

void loop(){}

Testing the code

The testing procedure will be the same we have been covering on previous posts. After compiling and uploading the code, simply open the serial monitor and copy the IP printed.

Next, open Postman to start sending the requests to the route we have configured in the code. We will try different HTTP methods, but the URL will always be the following (just change #yourDeviceIP# by the IP you have previously copied):

http://{yourDeviceIp}/test

We will start my making a HTTP GET request, by choosing that method from the methods dropdown of Postman. As shown in figure 1, upon sending the request, you should get the “ok” message we have defined as response, indicating that the request was successfully received by the server.

ESP32 HTTP server GET request success.png

Figure 1 – Result for the HTTP GET method request.

Next we will try the HTTP POST method. Note that we don’t need to define any body data, since our aim is just to check if the request is received by the server and correctly processed.

Upon sending the request, you should get an output like figure 2, also indicating success.

ESP32 HTTP POST request success.png

Figure 2 – Result for the HTTP POST method request.

To finalize we will send an PUT request. As shown in figure 3, for this case, the server will not process the request and give a 500 error code, since this method is not allowed on the route.

ESP32 HTTP server Put request rejected

Figure 3 – Result for the HTTP PUT method request.

7 thoughts on “ESP32 HTTP server: Multiple methods allowed on same route”

  1. Thanks so much man!! Great tutorials. I’ve got a bit of a question though, I’m trying to build a login system on my ESP32 via the ESP32’s IP.address and a browser.
    Is there an easy way to collect from data from the client via a POST request that does not require javaScript supplied via the Arduino server? JS is not a problem for me I’d just like to find a ‘leaner’ way of doing it. My sketch is nowhere near complete and already at 44% of the EPS32’s total capacity. Any suggestions? Thanks!,

    Keep up the good work;)

    1. Hi!

      Thanks for the feedback, I’m glad you are finding the content useful 🙂

      I’m actually writing a post on that 🙂 but you simply need to do the following call inside the route handling function:
      request->client()->remoteIP();

      So, complete code for the route:
      server.on(“/printIp”, HTTP_POST, [](AsyncWebServerRequest *request){

      request->send(200, “text/plain”, “ok”);

      Serial.print(“Received request from client with IP: “);
      Serial.println(request->client()->remoteIP());
      });

      This will basically access to the client object that is used under the hood to handle the exchange of data with the client.

      Be careful though about using IPs for login, IPs are really easy to fake by an attacker, so it’s not recommend to use as authentication / authorization mechanism.

      Hope this helps 🙂

      Best regards,
      Nuno Santos

  2. Thanks so much man!! Great tutorials. I’ve got a bit of a question though, I’m trying to build a login system on my ESP32 via the ESP32’s IP.address and a browser.
    Is there an easy way to collect from data from the client via a POST request that does not require javaScript supplied via the Arduino server? JS is not a problem for me I’d just like to find a ‘leaner’ way of doing it. My sketch is nowhere near complete and already at 44% of the EPS32’s total capacity. Any suggestions? Thanks!,
    Keep up the good work;)

    1. Hi!
      Thanks for the feedback, I’m glad you are finding the content useful 🙂
      I’m actually writing a post on that 🙂 but you simply need to do the following call inside the route handling function:
      request->client()->remoteIP();
      So, complete code for the route:
      server.on(“/printIp”, HTTP_POST, [](AsyncWebServerRequest *request){
      request->send(200, “text/plain”, “ok”);
      Serial.print(“Received request from client with IP: “);
      Serial.println(request->client()->remoteIP());
      });
      This will basically access to the client object that is used under the hood to handle the exchange of data with the client.
      Be careful though about using IPs for login, IPs are really easy to fake by an attacker, so it’s not recommend to use as authentication / authorization mechanism.
      Hope this helps 🙂
      Best regards,
      Nuno Santos

  3. Pingback: ESP32 Arduino web server: getting client IP | techtutorialsx

  4. Pingback: ESP32 Arduino web server: getting client IP | techtutorialsx

  5. Pingback: ESP32 Arduino: Temperature, humidity and CO2 concentration web server | techtutorialsx

  6. Pingback: ESP32 Arduino: Temperature, humidity and CO2 concentration web server | techtutorialsx

  7. Pingback: ESP32 Arduino web server: Add header to response | techtutorialsx

  8. Pingback: ESP32 Arduino web server: Add header to response | techtutorialsx

  9. Pingback: ESP32 Async HTTP web server: websockets introduction | techtutorialsx

  10. Pingback: ESP32 Async HTTP web server: websockets introduction | techtutorialsx

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading