Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation clarification. #1446

Open
rosenhauer opened this issue Nov 1, 2024 · 0 comments
Open

Documentation clarification. #1446

rosenhauer opened this issue Nov 1, 2024 · 0 comments

Comments

@rosenhauer
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant