Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a custom domain for a Cloud Function as a POST request

I'm not very experienced with Node.js but learning quick all do quite good with javaScript. I'm using Cloud Functions to create an API for a project and trying to use a custom domain to reach this API. On my Firebase Hosting, I have connected a subdomain "api.mydomain.com".

I have a function called "api" on my functions index.js using express:

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

app.post('/endpoint/:userId', (req, res) => {

  ... EXECUTE CODE 

  res.json(json);  

});

exports.api = functions.https.onRequest(app);

In my firebase.json I have a rewrite as so:

    "rewrites": [
  {
    "source": "/api/**",
    "function": "api"
  }

So in theory if I make a POST request to https://api.mydomain/api/endpoint/userID should execute the function but instead I get:

Cannot POST /api/endpoint/userID/

If I use the default firebase URL to access the function like https://us-central1-my-proyect.cloudfunctions.net/api it works fine.

Do you have any Idea how to properly configure the custom domain to work with my function?

Thanks a lot for any help!

like image 996
Xazzo Avatar asked Dec 26 '17 15:12

Xazzo


People also ask

What is the difference between onCall http callable and onRequest HTTP request functions?

onRequest creates a standard API endpoint, and you'll use whatever methods your client-side code normally uses to make. HTTP requests to interact with them. onCall creates a callable. Once you get used to them, onCall is less effort to write, but you don't have all the flexibility you might be used to.


1 Answers

When you use an Express app as the target for an HTTPS function, the name of the function gets prepended to the path of the hosting URL, just like it does when you call the function direction. There are two ways to compensate for this:

  1. Put the prefix path in your route paths:

    app.post('/api/endpoint/:userId', (req, res) => { ... })
    
  2. Create a second Express app that routes everything under /api, and send that to Cloud Functions:

    app.post('/endpoint/:userId', (req, res) => { ... })
    const app2 = express()
    app2.use('/api', app)
    exports.api = functions.https.onRequest(app2)
    

Either way, when you rewrite path /api/** to function api, your function will get invoked.

like image 111
Doug Stevenson Avatar answered Oct 31 '22 10:10

Doug Stevenson