1

I want to use firebase functions to host my expressjs webapp, however all get parameters seem undefined. Whats the problem?

    import functions= require("firebase-functions");
    import admin= require("firebase-admin");
    import express= require("express");
    import bodyParser= require("body-parser");
    const app: express.Application = express();
    admin.initializeApp();

    app.get("/getstory", async (req,resp)=>{
        try{
            const preferred_storyid=req.params.preferred_storyid;
            console.log(`preferred_storyid ${preferred_storyid}`) //logs preferred_storyid undefined. Why?
resp.send("ok");
        }catch (e) {
            resp.send(`erequest_story. ${e}`);
        }
    });
    const faststoryapi = functions.https.onRequest(app);
    module.exports={faststoryapi}

Then the code is deployed with

firebase deploy --only functions

and get request sent by post man enter image description here

PS: I have noticed that i cant have more than one route eg i cant have more than one post end point or else the second one is not called. How do you guys do it?

2 Answers 2

2
+50

You can do something like this:

...
app.get(async (req,resp) => { // no need of path
    try{
        const preferred_storyid=req.params.preferred_storyid;
        console.log(`preferred_storyid ${preferred_storyid}`) //logs preferred_storyid undefined. Why?
        resp.send("ok");
    } catch (e) {
        resp.send(`erequest_story. ${e}`);
    }
});

const faststoryapi = functions.https.onRequest(app);
module.exports={faststoryapi}

Now you can use your function by hitting the url: https://us-central1-<project-id>.cloudfunctions.net/faststoryapi. The api endpoint will be same as your exported function name, so you can change your function name accordingly.

If you are hosting an express app in cloud function you need to use req.query for url params.
Also in express req.params is used for paths like these:

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

So, what you are looking for is req.query.
See this answer for more info

Sign up to request clarification or add additional context in comments.

1 Comment

btw, actually you can have a whole express app in one cloud function, my bad. realised that just today when I tried it myself.
0

In Firebase Functions req and res objects are the same than ExpressJS's. To get query params you must use req.query.xxxx, while req.params.xxxx can be used to access path params.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.