为什么发送到ESP32 Arduino Web服务器的XMLHttpRequest中缺少JSON内容?

xhv8bpkk  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(147)

我有一个运行Web服务器的ESP32,它的UI需要以JSON格式向ESP发送对象数组。用户端的JSON字符串正确,esp收到请求,但不包含任何JSON内容。这是在用户端:

var dataWhite = [{hour: 10, minute:5, light:2000},{hour: 11, minute:10, light:2050}];
function uploadWhiteData() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/uploadWhiteData", true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
              if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
              }
            };
            xhr.send(JSON.stringify(dataWhite));
          }

在服务器端,我尝试像这样获取JSON:

server.on("/uploadWhiteData", HTTP_POST, [](AsyncWebServerRequest *request) {
    if (request->hasParam("plain", true)) {
      String data = request->getParam("plain", true)->value();
      Serial.print("Incoming JSON: ");
      Serial.println(data);
    }
    request->send(200);
  });

(in在这种情况下,hasParam()总是返回false),像这样:

server.on("/uploadWhiteData", HTTP_POST, [](AsyncWebServerRequest *request) {
  request->onRequestBody([](const String& body, size_t length) {
    if (request->header("Content-Type") == "application/json") {
      String data = body;
      Serial.print("Incoming JSON: ");
      Serial.println(data);

    }
  });

  request->send(200);
});

(with这个它打印“传入的JSON”,然后什么也没有)我也尝试了一个get请求,结果是相同的。

mcdcgff0

mcdcgff01#

有关如何创建HTTP_POST路由,请参阅设置服务器。您还可以看看我的示例here(向下滚动到“ESP32 Web服务器后端代码”部分,其中显示了main.cpp)。基本上API应该是:

server.on("/your_route", HTTP_POST, onRequest, onFileUpload, onBody);

由于Web服务器的异步特性,当接收到请求时,消息体还不可用,API用3个回调函数处理这个问题,每个回调函数在请求的不同阶段被调用,你正在做的方式,你希望在处理onRequest回调时请求体可用,它实际上只有在onBody回调被触发时才可用。

void onRequest(AsyncWebServerRequest *request) {
    // dummy callback function for handling params, etc.
}

void onFileUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) {
    // dummy callback function signature, not in used in this example
}

void onBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
  
    Serial.printf("body=%s\n", (char*) data);
    // deserialise the json data, do what you want with the data
    request->send(200, "text/plain", "Ok");
}

void setup() {
  // your setup code here 

  server.on("/uploadWhiteData", HTTP_POST, onRequest, onFileUpload, onBody);

  server.begin();
}

void loop() {

}

相关问题