【发布时间】:2020-12-29 17:00:55
【问题描述】:
我无法让 POST 方法与 ESP32 和 Async Web 服务器一起使用。准确地说,POST 路由被识别,但 body 处理失败。
ESP32 是 WROOM-32。 POST示例改编自ESP32 Arduino async HTTP server: Serving HTML
Web 服务器,实际上 ESP32 似乎以我尝试过的所有其他方式工作。虽然我下面的示例没有显示它,但 GET 方法工作得很好。当我尝试处理 POST 请求的正文时出现问题。我在代码“这里的代码不执行”中添加了注释,以显示什么不起作用。显示了简单的表单“/testform.html”,但提交时,POST 处理程序的标头部分显示内容类型为“application/x-www-form-urlencoded”,但 Chrome 浏览器没有返回任何内容,并且用于显示 POST 正文的打印语句不执行。
ESP32代码如下(我用的是Arduino IDE):
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"
const char* ssid = "xxxxxx"; // Actual SSID & Pw removed
const char* password = "xxxxxx";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Initialize SPIFFS
if(!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
Serial.println(WiFi.localIP());
server.on("/testform.html", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/testform.html", String(), false);
});
server.on(
"/my-handling-form-page",
HTTP_POST,
[](AsyncWebServerRequest * request) {
// The following print statements work + removing them makes no difference
// This is displayed on monitor "Content type::application/x-www-form-urlencoded"
Serial.print("Content type::");
Serial.println(request->contentType());
}, // Route handling function
NULL,
[](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
// *** Code here is NOT executed ***
for (size_t i = 0; i < len; i++) {
Serial.write(data[i]);
}
Serial.println();
request->send(200);
});
// Start server
server.begin();
}
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "My not found ***** ");
}
void loop()`{
}
“testform.htm”网页非常简单,在浏览器请求时按预期显示
<!DOCTYPE html>
<html>
<head>
<b>Test Form</b>
</head>
<body>
<form action="/my-handling-form-page" method="post">
<ul>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</li>
</ul>
<li class="button">
<button type="submit">Send your message</button>
</li>
</form>
</body>
</html>
我希望有人能找到明显的嘘声,或者给我一个线索,让我知道接下来我会尝试什么。
【问题讨论】:
-
我做了更多的研究并使用 Postman 进行了测试,当内容类型为“application/x-www-form-urlencoded”时,似乎没有调用 body 方法,即从我的简单 html 表单调用时的情况。在这种情况下,问题就变成了如何使用这种内容类型访问正文数据?