首页 > 解决方案 > ESP8266 POST request to Firebase Cloud HTTP Function returns Error 500 Could not handle the request

问题描述

It works fine with Postman but gives me an error when I try it through my ESP8266. Here is the code for the 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);
  }

And here is the Firebase Cloud Function:

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

Note the console.log(req.body) in the Cloud Function. I can see the log when trying with Postman but when trying with the ESP chip the function doesn't even reach till the console.log line and just says function exited with status 'crash' in the logs.

I am pulling my hair out here trying to figure out what is going wrong. Any help is appreciated.

标签: jsonpostgoogle-cloud-functionsesp8266

解决方案


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

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

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

推荐阅读