来自 ESP8266 的 Firestore REST API POST 请求

Firestore REST API POST request from ESP8266

我正在尝试从 ESP8266 中将一条信息保存在 Cloud Firestore 中。

我已经为此修改了示例代码。

我试过GET请求,成功返回了我之前存储的文档。但是,当我尝试 POST 请求时,出现以下错误:

{
  "error": {
    "code": 400,
    "message": "Document parent name \"projects/dummy-1cb41/databases/(default)/documents/users\" lacks \"/\" at index 56.",
    "status": "INVALID_ARGUMENT"
  }
}

我想我没有正确实现 json 负载主体。试了很多次都做不好。

请帮忙!

这是代码

/**
   BasicHTTPSClient.ino

    Created on: 20.08.2018

*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClientSecureBearSSL.h>
// Fingerprint for demo URL, expires on June 2, 2021, needs to be updated well before this date
const uint8_t fingerprint[20] = {0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3};

ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("ssid", "password");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);

//    client->setFingerprint(fingerprint);

    client->setInsecure();

    HTTPClient https;

    String url = "https://firestore.googleapis.com/v1beta1/projects/dummy-1cb41/databases/(default)/documents/users/doc-1";

    Serial.print("[HTTPS] begin...\n");
    if (https.begin(*client, url)) {  // HTTPS

      Serial.print("[HTTPS] GET...\n");
      // start connection and send HTTP header
//      int httpCode = https.GET();
      https.addHeader("Content-Type", "application/json");
 
      int httpCode = https.POST("{\"fields\":{\"name\":{\"stringValue\":\"a name\"}}}");
      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = https.getString();
          Serial.println(payload);
        } else {
          Serial.println(https.getString());
        }
      } else {
        Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
      }

      https.end();
    } else {
      Serial.printf("[HTTPS] Unable to connect\n");
    }
  }

  Serial.println("Wait 10s before next round...");
  delay(10000);
}

我已经解决了问题。感谢 Luis Manuel 和 Ben T 的评论和提示。

问题是我犯了一个愚蠢的错误,将 GET 请求的相同 URL 用于 POST 请求。这意味着我试图在 Firestore 中的文档内创建文档,而在文档内创建文档是不可能的。新文档必须在集合中创建。因此,在通过删除末尾的 doc-1 来更正 URL 之后,新的 URL 将像这样 .../users/。它工作得很好。