ESP8266 对 Firebase Cloud HTTP 函数的 POST 请求返回错误 500 无法处理请求

时间:2021-03-07 08:11:03

标签: json post google-cloud-functions esp8266

它在 Postman 上运行良好,但当我通过 ESP8266 尝试时出现错误。这是 ESP8266 的代码:

if(buttonState == HIGH) //send notification when button pressed
  {
    HTTPClient http;
    WiFiClientSecure client;
    client.setInsecure();
    //client.setFingerprint("A5:D4:06:4C:2A:4B:46:CD:C4:A5:51:7F:4C:F6:62:92:60:90:FD:37");
    http.begin(client, notifUrl);
    http.addHeader("Content-Type", "Content-Type: application/json"); 
    int httpResponseCode = http.POST(input);
    if(httpResponseCode>0)
    {
      String response = http.getString();  //Get the response to the request
      Serial.println(httpResponseCode);   //Print return code
      Serial.println(response);           //Print request answer
    } 
    else 
    {
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
      http.end();
    }
    delay(1000);
  }

这是 Firebase 云函数:

exports.sendNotification = functions.https.onRequest((req, res) => {

  // Check for POST request
  if(req.method !== "POST"){
    res.status(400).send('Please send a POST request');
    return;
    }

    console.log(req.body);

    var message = {
        data: {
          title: 'Someone is at the door',
          body: 'Always check who it is before unlocking your door :)'
        },
        android: {
          priority: 'high',
        },
        token: req.body.token
      };

    // Send a message to the device corresponding to the provided
    // registration token.
    admin.messaging().send(message)
        .then((response) => {
            // Response is a message ID string.
            console.log('Successfully sent message:', response);
            res.status(200).send('Message sent successfully');
        })
        .catch((error) => {
            console.log('Error sending message:', error);
            res.status(500).send("Error sending message");
        });
});

注意 Cloud Function 中的 console.log(req.body)。尝试使用 Postman 时我可以看到日志,但是当尝试使用 ESP 芯片时,该功能甚至没有到达 console.log 行,只是说功能退出,日志中的状态为“崩溃”。

我在这里拔头发,试图弄清楚出了什么问题。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这里的问题一定是因为您发送了错误的 HTTP Content-Type 标头。 您发送的是 Content-Type: Content-Type: application/json,而不是 Content-Type: application/json,我猜 Firebase 不太喜欢它!

在您的代码中,它应该是:

http.addHeader("Content-Type", "application/json");