I am facing issues with Firebase functions where the parameters received from Express.js routes are

I am encountering an issue while trying to use firebase functions to host my expressjs webapp. For some reason, all get parameters appear to be undefined. Can anyone help me figure out what the problem might be?

    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}

After writing the code above, I deploy it using the command:

firebase deploy --only functions

I then send a GET request using Postman and encounter issues. You can view the screenshot https://i.sstatic.net/YChGg.png

PS: Another problem I have noticed is that I am unable to have more than one route. For example, having more than one post endpoint results in the second one not being called. How do you guys work around this limitation?

Answer №1

If you want to achieve a similar result, consider the following code snippet:

...
app.get(async (req,resp) => { // no path needed
    try{
        const preferred_storyid=req.params.preferred_storyid;
        console.log(`preferred_storyid ${preferred_storyid}`) //displays preferred_storyid as undefined. Any idea why?
        resp.send("ok");
    } catch (e) {
        resp.send(`erequest_story. ${e}`);
    }
});

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

You can access your function through the URL:

https://us-central1-<project-id>.cloudfunctions.net/faststoryapi
. The endpoint for the API will match the name of your exported function.

When hosting an express app in cloud functions, use req.query for URL parameters.
In Express, req.params is utilized for paths like the one shown below:

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

Therefore, you should make use of req.query instead of req.params.
Refer to this response for additional information.

Answer №2

Within Firebase Functions, the req and res objects function similarly to those in ExpressJS. To fetch query parameters, utilize req.query.xxxx, whereas req.params.xxxx is used for retrieving path parameters.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An ongoing challenge with user authentication in Express.js and Passport.js using a dynamic IP server on no-ip.org: the authentication process keeps

I have exhaustively searched for a solution to this issue. The application functions correctly when operated as localhost, keeping users authenticated for an extended period. However, when I run it on my server and log in, it seems like the connection rese ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration: Globals: Function: Timeout: 30 Environment: Variables: DBNAME: !Ref DBNAME Resources: MessageFunction: Type: AWS::Serverless: ...

Searching in MongoDB: Using a dynamic regular expression in $where clause

As I work on my nodejs express web application using a mongo db, I have encountered an issue with searching for authors based on their first and last names. Here is the schema for the Author: const AuthorSchema = new Schema({ first_name: { type: Strin ...

Sending SQL data to a Node.js module upon receiving a client request

Currently, I am establishing a connection to a SQL database and retrieving data on the view by using res.json. The client initiates a request - my server employs an MSSQL driver and a connection string to establish a connection with the database and fetch ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

React: Dealing with unsuccessful imports

Whenever a device loses internet connection, my app crashes due to an imported component that relies on Google Maps. To address this issue and prevent the app from showing a blank screen, I want to intercept the failed Google Maps import and display an err ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Why does Angular routerlink display %20 before the id path?

In my quest to showcase messages from a nested collection of messages, I have encountered a peculiar issue. When clicking on the "view" tag within certain cards, I use routerlink to navigate to the intended path where messages are displayed. Strangely en ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

Tips on excluding specific files in a folder while rendering with Express using `fs.readdir`

I'm currently working on an express/node app and I have the following code snippet in my index.js file: // BACKGROUNDS fs.readdir('public/img/backgrounds/',function(err,files){ if(err) throw err; files.forEach(function(file){ myBGfi ...

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code. MainContainer.vue <template> <div class="main-container" r ...

Using `await` or `then` with a Promise object can lead to varying results

Here is an example of code that compiles successfully import yargs from "yargs"; const parser = yargs(process.argv.slice(2)). usage("$0 [filename]"). demandCommand(1); async function main() { const argv = await parser.argv ...

What are best practices for implementing JWT for authentication purposes?

Scenerio Example: In my frontend, I am using HTML and JS. In the backend, Express is being used. JWT is used for authentication. I understand that JWT is typically placed in the Authorization header when sent back to the server. What I need help with: ...

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

Transferring information from Node.js to HTML with the help of EJS template engine

Below is the Server Side code I am using: app.set('view engine', 'html'); app.engine('html', require('ejs').renderFile); app.use(express.static('views')); app.use(bodyParser.urlencoded({extended:true})); a ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...