如何在POST请求期间将键值对添加到req.body字典

时间:2019-02-10 22:50:08

标签: javascript express nedb

我正在使用NEDB和Express / Node。

这是我的API:

app.post('/api/texts/', function (req, res, next) {

    (req.body).push({
      key:   "additionalField",
      value: 0
    });

    texts.insert(req.body, function (err, text) {
        if (err) return res.status(500).end(err);
        return res.json(text);
    });
});

我正在尝试将自己的键添加到主体字典中(我希望键值是一个整数)。

当前ode给我一个错误,提示“ TypeError:req.body.push不是函数”。

1 个答案:

答案 0 :(得分:2)

您为什么不新建一个对象?例如:

// import the headers
#include <ESPmDNS.h>

void findMyPi() {
  Serial.println("Finding the mDNS details...");

  // make sure we are connected to the Wifi
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.println("Not yet connected to Wifi...");
  }

  if (!MDNS.begin("whatever_this_could_be_anything")) {
    Serial.println("Error setting up MDNS responder!");
  }

  // what should I put in here as "service"?
  int n = MDNS.queryService("mqtt-broker", "tcp");
  if (n == 0) {
    Serial.println("No services found...");
  }
  else {
    for (int i = 0; i < n; ++i) {
      // Print details for each service found
      Serial.print("  ");
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(MDNS.hostname(i)); // "mqtt-broker" ??? How can I find it???
      Serial.print(" (");
      Serial.print(MDNS.IP(i));
      Serial.print(":");
      Serial.print(MDNS.port(i));
      Serial.println(")");
    }
  }
  Serial.println("Done finding the mDNS details...");
}

或者您可以简单地使用app.post('/api/texts/', function (req, res, next) { const obj = {}; for (let [key, value] of Object.entries(req.body)) { obj[key] = value; } obj.additionalField = 0; texts.insert(obj, function (err, text) { if (err) return res.status(500).end(err); return res.json(text); }); }); 而不是创建新对象