Arduino-ESP 8266 踩坑(一) ESPAsyncWebServer AsyncCallbackJsonWebHandler
在使用 ESPAsyncWebServer 时 由于我想用 asyncWebServer 通过 application/json POST 请求拿数据, 就翻看了 ESPAsyncWebServer 的 git 文档, 他是这样说的 :
//JSON body handling with ArduinoJson
//Endpoints which consume JSON can use a special handler to get ready to use JSON data in the request callback:
#include "AsyncJson.h"
#include "ArduinoJson.h"
AsyncCallbackJsonWebHandler* handler = new AsyncCallbackJsonWebHandler("/rest/endpoint", [](AsyncWebServerRequest *request, JsonVariant &json) {
JsonObject& jsonObj = json.as<JsonObject>();
// ...
});
server.addHandler(handler);
编译报错:
error: cannot bind non-const lvalue reference of type ‘ArduinoJson::V6213PB2::JsonObject&’ to an rvalue of type ‘ArduinoJson::V6213PB2::detail::enable_if<true, ArduinoJson::V6213PB2::JsonObject>::type’ {aka ‘ArduinoJson::V6213PB2::JsonObject’}
44 | JsonObject &jsonObj = json.as();
我承认我很菜,但是对于一个仅初步学习过 C/C++ 的初学者来说, 我很难找到问题.
于是乎我又跑去翻看 ArduinoJson 的文档:
官网 Example
StaticJsonDocument<256> doc;
JsonObject object = doc.to<JsonObject>();
object["hello"] = "world";
const char* world = object["hello"];
我才发现 AsyncCallbackJsonWebHandler 文档上面的代码有一点小问题, 就是这句话:
JsonObject& jsonObj = json.as<JsonObject>();
所以 请去掉 & 符号, 这个问题困扰了我一天, 该文长点记性
所以正确的写法应该是:
AsyncCallbackJsonWebHandler *handler =
new AsyncCallbackJsonWebHandler("/updateSetObj",
[](AsyncWebServerRequest *request, JsonVariant &json)
{
JsonObject jsonObj = json.as<JsonObject>();
const char* lpwm = jsonObj["lPwm"];
Serial.println("------------------");
Serial.println(lpwm);
request->send(200, "application/json", "{\"code\": 1}");
});
server.addHandler(handler);
结果