webserveresp32esp8266url-parameterspath-parameter

ESP WebServer Handle Path Parameters


I'm having a problem handling requests on an ESP that acts as WebServer. Basically this code:

#include <WebServer.h> //using this library
...   
        webServer.on("/api/:userId/lights", HTTP_GET, [this]() { handle_GetState(); });
        webServer.on("/api/:userId/lights/:num", HTTP_GET, [this]() { handle_GetState(); });
        webServer.on("/api/:userId/lights/:num/state", HTTP_PUT, [this]() { handle_PutState(); });
        webServer.on("/", HTTP_GET, [this]() { handle_root(); });
        webServer.on("/debug/clip.html", HTTP_GET, [this]() { handle_clip(); });
        webServer.onNotFound( [this]() { handle_CORSPreflight(); });

is supposed to handle dynamic path parameters but when making a request (example: /api/USERXXX/lights) it's always handled by onNotFound function.

I've tried to replace ':userId' with '{}', '{userId}', '<userId>', but nothing seems to work. Obviously when calling http://192.168.XXX.XXX/api/:userId/lights the webserver retrieves the right response so the path parameter notation is not recognized.

Anyone knows which is the right way to do it?


Solution

  • Seems like your endpoint would need to be something like this:

    webServer.on(UriRegex("^\\/api\\/(.*)\\/lights$"), HTTP_GET, [this]() { handle_GetState(); });
        webServer.on(UriRegex("^\\/api\\/(.*)\\/lights\\/([0-9]+)$"), HTTP_GET, [this]() { handle_GetState(); });
        webServer.on(UriRegex("^\\/api\\/(.*)\\/lights\\/[0-9]+\\/state$"), HTTP_PUT, [this]() { handle_PutState(); });
        webServer.on("/", HTTP_GET, [this]() { handle_root(); });
        webServer.on("/debug/clip.html", HTTP_GET, [this]() { handle_clip(); });
        webServer.onNotFound( [this]() { handle_CORSPreflight(); });
    

    Using the URI Regex you can then leverage a reference to webServer within your endpoint handling functions to do something like this:

    String userId = webServer.pathArg(0);
    String lightNum = webServer.pathArg(1);
    

    That should allow you to get at the captured portions of the regex URI. Incase you are new to Regex the captured portions are the portions of the regex statement which are in Parens '()' the first capture is index 0 and then so on from there.