Arduino ESP 8266 ESPAsyncWebServer AsyncCallbackJsonWebHandler

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);

结果
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值