Skip to content
This repository was archived by the owner on Jan 20, 2025. It is now read-only.
This repository was archived by the owner on Jan 20, 2025. It is now read-only.

Documentation clarification. #1446

@rosenhauer

Description

@rosenhauer

I was transitioning from the basic WebServer to ESPAsyncWebServer and was using js to send (Fetch) Requests

const request = new Request("http://192.168.0.80/sendcommand", {
      method: "POST",
      mode: "cors", // no-cors, cors, *same-origin
      body: JSON.stringify({ command: theCommand , password: '1234'}),
    });
    fetch(request)
    .then((response) => {
      if (response.status === 200) {
        return;
        //return response.json();
      } else {
        throw new Error("Something went wrong on API server!");
      }
    })
    .catch((error) => {
      console.error(error);
    });

This was working fine under the old WebServer but I wanted to add LittleFS support to server files from the SPIFF partition.

After converting I wasn't getting the "sendCommand" message body. Took some searching to find out how to get it.

server.on("/sendcommand", HTTP_POST, [](AsyncWebServerRequest *request){
    //do nothing and don't remove it
  }, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
    JsonDocument body;
    DeserializationError error = deserializeJson(body, (const char*)data);
    
    String theCommand;
    String thePassword;

    if (!error) {
      if (body.containsKey("command")) {
        theCommand = String(body["command"].as<String>());
      }
      if (body.containsKey("password")) {
        thePassword = String(body["password"].as<String>());
      }

      Serial.printfln("Command:%s Password=%s", theCommand.c_str(), thePassword.c_str());
      // Do something with the payload...

      request->send(200, "text/plain", "success");
    } else {
      request->send(404, "text/plain", "");
    }
  });

Again not an issue but rather that it took forever to find that the server.on function has a version with three calls and that the third one is what will process the body. Feel free to close. But I wanted to document it for others.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions