【问题标题】:firebase functions using expressjs routes get parameters undefined使用expressjs路由的firebase函数获取未定义的参数
【发布时间】:2020-07-08 22:47:06
【问题描述】:

我想使用 firebase 函数来托管我的 expressjs webapp,但是所有 get 参数似乎都未定义。有什么问题?

    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}

然后代码部署用

firebase deploy --only functions

并获取邮递员发送的请求

PS:我注意到我不能有多个路线,例如我不能有多个后端点,否则不会调用第二个。你们是怎么做到的?

【问题讨论】:

    标签: typescript firebase express google-cloud-functions


    【解决方案1】:

    在 Firebase 函数中,reqres 对象与 ExpressJS 的对象相同。 要获取查询参数,您必须使用req.query.xxxx,而req.params.xxxx 可用于访问路径参数

    【讨论】:

      【解决方案2】:

      你可以这样做:

      ...
      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}
      

      现在您可以通过点击 url 来使用您的功能:https://us-central1-<project-id>.cloudfunctions.net/faststoryapi。 api 端点将与您导出的函数名称相同,因此您可以相应地更改函数名称。

      如果您在云功能中托管快速应用程序,您需要使用 req.query 获取 url 参数。
      同样在 express req.params 用于如下路径:

      路由路径:/users/:userId/books/:bookId
      请求网址:http://localhost:3000/users/34/books/8989
      req.params: { "userId": "34", "bookId": "8989" }

      所以,您要查找的是req.query
      请参阅此answer 了解更多信息

      【讨论】:

      • 顺便说一句,实际上你可以在一个云功能中拥有一个完整的快递应用程序,我的错。就在今天我自己尝试时才意识到这一点。
      猜你喜欢
      • 2013-06-14
      • 2018-12-08
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多