wahab
wahab

Reputation: 835

ESP8266 JSON Parameters in HTTP_POST Request

I am working on a project in which the ESP8266 starts in softAP mode on start up. The homepage displays a list of available WiFi networks. The user selects one of them and enters the password for that network. This sends a HTTP_POST request to the web server which includes the SSID, and password of the selected WiFi network a JSON list. But when I check the number of parameters for the request, I'm getting 0. The server identifies the content type and content length correctly, but it can't recognize any parameters. Here is the code for the /connect handle. I have also tried using request->args(). That doesn't work either.

server.on("/connect", HTTP_POST, [](AsyncWebServerRequest *request)
{
    String argList;
    String password;
    String key = "ssid";
    Serial.println(request->contentType());
    Serial.println(request->contentLength());
    Serial.print("ArgNum: ");
    Serial.println(request->params());
    for (int i = 0; i < request->params(); i++)
    {
        AsyncWebParameter* p = request->getParam(i);
        Serial.print(p->name());
        Serial.print(": ");
        Serial.println(p->value());
    }

    request->send(200, "text/plain", "SUCCESS");
});

Upvotes: 0

Views: 1781

Answers (1)

wahab
wahab

Reputation: 835

I had to parse the request body using a json parser.

server.on("/connect", HTTP_POST, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", "SUCCESS");
}, NULL, onConnectBody);

void onConnectBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
{
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(data);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

String ssid = root["ssid"];
String password = root["password"];
bool secure = root["secure"];

Serial.print("ssid: ");
Serial.println(ssid);
Serial.print("password: ");
Serial.println(password);
Serial.println(secure);
setNetworkCredentials(ssid, password, secure);
}

Upvotes: 3

Related Questions