Manspof
Manspof

Reputation: 357

http post request firebase cloud function

I want to make post request and send data into body in firebase cloud function. as default, it is get request or post request?

 var functions = require('firebase-functions');

exports.tryfunction= functions.https.onRequest((req, res) => {
    console.log(req.body) // or it should be req.query 
});

how do I know and decide what the method it is?

Upvotes: 3

Views: 9462

Answers (3)

Nimrod Dayan
Nimrod Dayan

Reputation: 3100

To specify the HTTP method that your Firebase Function accepts you need to use Express API as you'd normally do in a standard Express app.

You can pass a full Express app to an HTTP function as the argument for onRequest(). This way you can use Express' own API to restrict your Firebase function to a specific method. Here's an example:

const express = require('express');
const app = express();

// Add middleware to authenticate requests or whatever you want here
app.use(myMiddleware);

// build multiple CRUD interfaces:
app.get('/:id', (req, res) => res.send(Widgets.getById(req.params.id)));
app.post('/', (req, res) => res.send(Widgets.create()));
app.put('/:id', (req, res) => res.send(Widgets.update(req.params.id, req.body)));
app.delete('/:id', (req, res) => res.send(Widgets.delete(req.params.id)));
app.get('/', (req, res) => res.send(Widgets.list()));

// Expose Express API as a single Cloud Function:
exports.widgets = functions.https.onRequest(app);

Explanation of the above code: We expose a Firebase function with endpoint /widgets with different handlers for different HTTP methods using Express' own API, e.g. app.post(..), app.get(..), etc. We then pass app as an argument to functions.https.onRequest(app);. That's it, you're done!

You can even add more paths if you wish, E.g. if we want an endpoint that accepts GET requests to an endpoint that looks like: /widgets/foo/bar, we simply add app.get('/foo/bar', (req, res => { ... });.

It's all taken directly from the official Firebase docs. I'm surprised @Doug Stevenson didn't mention this in his answer.

Upvotes: 0

Oğuzhan TANYAŞ
Oğuzhan TANYAŞ

Reputation: 96

I just sharing simple code part. I'm using like this.

const functions = require('firebase-functions');


 exports.postmethod = functions.https.onRequest((request, response) => {
  if(request.method !== "POST"){
    response.send(405, 'HTTP Method ' +request.method+' not allowed');
    }

  response.send(request.body);
 });

I hope it will be helpful.

Upvotes: 8

Doug Stevenson
Doug Stevenson

Reputation: 317467

There is no default. The request method is whatever the client chose to send.

The req object in your callback is an express.js Request object. Use the linked documentation, you can see that the request method can be found by using req.method.

Upvotes: 2

Related Questions