【问题标题】:Firebase function get parameter from URLFirebase 函数从 URL 获取参数
【发布时间】:2018-10-13 20:54:58
【问题描述】:

我想要一个像https://<my-project-id>.firebaseapp.com/parameter 这样的自定义网址,这样我就有一个函数可以接收值'parameter'。

这是我对 firebase.json 重写的内容:

"rewrites": [
      {
        "source": "/:bar*", "function": "foo"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]

然后对于函数/index.js,这里是我的 'foo' 函数:

exports.foo = functions.https.onRequest((req, res) => {
  console.log('bar = '+req.query.bar);
  console.info(req.query.bar);
  res.status(200).send(`<!doctype html>
    <head>
      <title>Test</title>
    </head>
    <body>
      Bar = ${req.query.bar}
    </body>
  </html>`);
});

什么有效,但不是我想要的

如果我将 firebase.json 更改为以下内容:

"rewrites": [
      {
        "source": "/**", "function": "foo"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]

把网址写成这样:

https://<my-project-id>.firebaseapp.com/anything?bar=test

然后它正确地获取 bar 参数。但是,我需要能够缩短 url。

【问题讨论】:

    标签: node.js firebase google-cloud-functions firebase-hosting


    【解决方案1】:

    尝试console.log(req.url); 获取网址。然后你只需要提取/之后的最后一部分

    【讨论】:

    • 这是我得到的:Your client does not have permission to get URL /foo from this server
    • 让我再检查一下
    • 糟糕,很抱歉。我已经清理了我的代码以发布并忘记了。所以我把函数名弄错了。您的解决方案完美运行。谢谢!
    • 应该注意的是,当您在 Cloud Functions HTTP 触发器中处理请求和响应时,实际上是在使用 Express.js API。 expressjs.com/en/api.html#req
    【解决方案2】:

    根据其他答案,这就是我为使“getUser”请求工作所做的工作:

    exports.getUser = (req, res) => {
    // https://us-central1-project.cloudfunctions.net/api/user/diegovfeder
    // console.log(req.url);
    
    let userId = req.url.split("/");
    userId = userId[userId.length - 1];
    
    //console.log(userId);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 2014-05-12
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多