ESP32 Arduino web server: Add header to response

In this tutorial we will check how to add a header to the response sent back to the client when he makes a request to an endpoint of an HTTP server hosted by the ESP32, on the Arduino core. The tests were performed using a DFRobot’s ESP32 module integrated in a ESP32 development board.

Introduction

In this tutorial we will check how to add a header to the response sent back to the client when he makes a request to an endpoint of an HTTP server hosted by the ESP32, on the Arduino core.

If you haven’t yet installed the HTTP async web server libraries for the Arduino core, please check this previous post on how to do it.

The tests were performed using a DFRobot’s ESP32 module integrated in a ESP32 development board.

The code

The initial part of the code is the same that we have been covering in the past HTTP async web server tutorials. We start by including the libraries needed to connect the ESP32 to a WiFi network and to setup the server, and then we declare the credentials of the WiFi network.

Additionally, we declare an object of class AsyncWebServer, passing as input of the constructor the port where the server should listen to incoming HTTP requests.

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

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

AsyncWebServer server(80);

Moving on to the Arduino setup function, we first open a serial connection and then connect the ESP32 to the WiFi network. After the connection is established, we print the local IP assigned to the ESP32, so we can later use it to make the HTTP request from a client.

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 can handle the route declaration. We will declare a route called “/header” that will be listening to HTTP GET requests.

server.on("/header", HTTP_GET, [](AsyncWebServerRequest *request){
// Route handling function
});

Now, in the handling function, we will need to build the response in parts before actually sending to the client, which is different from what we have been doing in past tutorials.

So, the first thing we need to do is calling the beginResponse method on the request object that we receive in our route handling function. Note that since we don’t directly receive the request object but rather a pointer to it, then we need to use the -> operator in order to call the beginResponse method.

As input of the method, we will pass 3 parameters. The first one is the HTTP response code, which will be 200 (corresponds to OK). As second parameter we will pass the content-type, which will be “text/plain“. As third parameter we will pass the actual content to be returned to the client, which will be a simple “Ok” string.

Note the similarity between the inputs we pass to this method and the ones we would pass if we returned the response immediately using the send method of the request object.

As output, this method call will return a pointer to an object of class AsyncWebServerResponse, which we will store in a variable.

AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Ok");

Now, to add an header to the response before it is sent, we simply need to call the addHeader method on our response object. Again, since we have a pointer to the response object, we need to use the -> operator.

This method receives as first input the name of the header we want to add to the response and as second the content of the header. I will be adding a dummy testing header, but you can use this for any other type of header.

response->addHeader("Test-Header", "My header value");

Finally, to send the actual complete response, we call the send method on the request object, passing as input the pointer to our response object.

request->send(response);

With this, we conclude the route handling function. Now, to finalize the Arduino setup function, we need to call the begin method on our server object. After this call, it will start listening to incoming requests.

server.begin();

The final code can be seen below.

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

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

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("/header", HTTP_GET, [](AsyncWebServerRequest *request){
    AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Ok");
    response->addHeader("Test-Header", "My header value");
    request->send(response);
  });

  server.begin();
}

void loop(){}

Testing the code

To test the code, simply compile it and then upload it to your device. Once the procedure finishes, open the Arduino IDE serial monitor.

After the ESP32 finishes the connection to the WiFi network, it should output the local IP assigned to it. Copy that IP, so we can use it to reach the server.

Next, open a web browser of your choice and type the following, changing #yourIP# by the IP you have just copied from the serial monitor:

http://#yourIP"/header

You can check the expected result from accessing that link at figure 1. As can be seen, the header we have specified in the code was indeed added to the response sent back to the client.

ESP32 Arduino HTTP web server add header to response.png

Figure 1 – Header added to the response.

Related Posts

7 Replies to “ESP32 Arduino web server: Add header to response”

  1. hi testing the code got an error:
    ‘gt’ was not declared in this scope

    how to solve ?

    how to get the status of a output pin as a response to a post response ?

    1. Hi!

      Sorry, WordPress was escaping the greater then character to “gt” and thus the final code was giving problems when compiling.

      It should be fixed now 🙂

      Best regards,
      Nuno Santos

  2. H .friend.thank you for your work.how to add header when serving javascript from file system.i want to send gzip javascript from file system.if possible make tutorial for this.thanks

    1. Hi,

      You’re welcome 🙂

      You have here an example on how to serve JavaScript from the file system:
      https://techtutorialsx.com/2018/10/04/esp32-http-web-server-serving-external-javascript-file/

      For both things (header + serving from gile system) you can check here, at the library GitHub page:
      https://github.com/me-no-dev/ESPAsyncWebServer#respond-with-content-coming-from-a-file-and-extra-headers

      But note that just adding a gzip header to the response won’t make the content gzip encoded. You need to either do the compression on the ESP32 before serving the file or store the file already compressed in the file system.

      If you want to do the compression on the ESP32, my recommendation is to explore zlib.
      https://zlib.net/

      You can copy the content of the folder from the link below and paste it in a folder in the Arduino libraries and it should be importable to your code (inside an extern “C” block). I’ve ran some quick tests in the past and I was able to achieve some results.
      https://github.com/loboris/ESP32_curl_example/tree/master/components/zlib

      Best regards,
      Nuno Santos

    1. Hi!

      It was solved in the past, but recently popped up again since the infra structure where the site was hosted changed.

      The syntax highlight plugin available here is different (it doesn’t deal in the same way with the g t ; and l t ; escapings), which is causing a lot of headaches.

      Currently, I have to go post by post solving the issue, which takes a lot.

      I’t should have been solved now on this post, please let me know if it is compiling now.

      In the meanwhile, if you find more posts with this issue, feel free to leave there a comment to make my life easier and know where I have to go next 🙂

      Sorry for the trouble.

      Best regards,
      Nuno Santos

Leave a Reply