How do Cloud Firebase functions handle the HTTP post method?

I created a Firebase Cloud Functions application, I created a function with https.onRequest . and get the data using req.body , but there is no data there.

Can Firebase cloud functions handle the HTTP POST method?

This is my sample code: -

 var functions = require('firebase-functions'); exports.testPost = functions.https.onRequest((req, res) => { console.log(req.body); }); 

I tested the postman with the POST method, but did not show the result in the Firebase log.

+6
source share
3 answers

I plan to do the same. I believe the approach should be to check request.method in the function body. A likely approach could be:

 if (request.method != "POST") { respond.status(400).send("I am not happy"); return; } // handle the post request 

Here is some link for details regarding the request object: https://firebase.google.com/docs/functions/http-events

+4
source

Your project may not be configured to communicate with your firebase database. Follow these steps with the terminal:

npm install -g firebase-tools

Then in the project folder run the following command and log in using your credentials

firebase login

Then

firebase init functions

This will create a folder with index.js, package.json and node_modules

If you use Postman correctly, the rest of your code should work.

0
source

Functions built on Firebase can also use Express.js routers to handle GET / POST / PUT / DELETE, etc., which are fully supported by Google and are the recommended way to implement these types of functions.

Further documentation can be found here:

https://firebase.google.com/docs/functions/http-events

Here is a working example built on Node.js

 const functions = require('firebase-functions'); const express = require('express'); const cors = require('cors'); const app = express(); // Automatically allow cross-origin requests app.use(cors({ origin: true })); app.get('/hello', (req, res) => { res.end("Hello world from Firebase!"); }); // Expose Express API as a single Cloud Function: exports.widgets = functions.https.onRequest(app); 

Then run firebase deploy, and this should compile your code and create a new widgets function. Note. You can rename widgets to any place. Ultimately, it will generate a URL to call the function.

0
source

Source: https://habr.com/ru/post/1265857/


All Articles