3

I currently have the following code

server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("ON hit.");
    String message;
    Serial.println(request->url());
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = " not specified";
    }
    request->send(200, "text/plain", "On, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);
....

When sending in a request I get the out put, "Device not specified".

I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:

server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("OFF hit.");
    String message;
    int params = request->params();
    Serial.printf("%d params sent in\n", params);
    for (int i = 0; i < params; i++)
    {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isFile())
        {
            Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
        }
        else if (p->isPost())
        {
            Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
        }
        else
        {
            Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
        }
    }
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = "not specified";
    }
    request->send(200, "text/plain", "Off, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);

and get the output now of

1 params sent in
_POST[device]: puddle
Device not specified  

If I try to do something like request->getParam(0)->value().c_str() I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.

rball
  • 133
  • 1
  • 1
  • 3
  • 2
    try `hasParam("device", true)` – Juraj Oct 04 '18 at 09:46
  • usually params are for GET while POST has a separate interface – dandavis Oct 04 '18 at 16:09
  • @Juraj that was it. Want to make an answer? Lol, feel pretty silly. – rball Oct 05 '18 at 03:52
  • 2
    just in case, someone finds this snipplet: In addition to @Juraj (correct) answer: If you want to access this param you also have to inform the function, that you want the url parameters: `message = request->getParam("device", true)->value();` – Dakkar May 15 '20 at 17:09

1 Answers1

3

For POST request the hasParam needs to know if you want to test the url parameters or x-www-form-urlencoded parameters in body of the POST request. The second parameter of the hasParam is boolean post and it has default value false. Use hasParam("device", true).

Juraj
  • 17,050
  • 4
  • 27
  • 43