Search code examples
jsonpostgoogle-cloud-functionsesp8266

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.


Solution

  • The issue here must be because you are sending a wrong HTTP Content-Type header. You are sending Content-Type: Content-Type: application/json, instead of Content-Type: application/json, I guess Firebase doesn't like it too much!

    In your code it should then be:

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