代码之家  ›  专栏  ›  技术社区  ›  Paul Renshaw

Vue。Firebase托管上的js SPA,使用通配符重写Firebase云函数

  •  0
  • Paul Renshaw  · 技术社区  · 8 年前

    我有一个vue。使用vue路由器的js应用程序。如果我使用firebase托管在默认公共目录中为应用程序提供服务,并尝试使用https功能,则不会调用该功能,因为路由器会拾取路径并尝试呈现路由。

    我将应用程序移动到public/app并更改了firebase。json会相应地重写(通过访问以/app/**结尾的URL,我的应用程序内容可以正常工作),但我仍然无法运行这些函数。

    我尝试使用通配符重写,如下所示

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

    但这也不起作用(我不确定它是否是用于函数的,我在任何地方都找不到示例)。

    e、 g.我使用了默认函数索引。js(并取消了helloWorld函数的注释),因此期望/helloWorld从helloWorld函数输出响应(正如我前面所说的,如果我导航到/app/route,我将从vue应用程序获得预期的输出)。

    这样行吗?还是我需要做一些完全不同的事情?

    ------编辑

    在Doug的评论之后,我将我的函数脚本更新为

    import * as functions from 'firebase-functions';
    import * as admin from 'firebase-admin';
    import * as express from 'express';
    
    const app = express();
    
    app.get("/:function", (req, res) => {
        switch(req.params.function) {
    
            case 
                "helloWorld" : helloWorld(res)
                break;
    
            default : res.send("Invalid function requested.")
    
        }
    });
    
    function helloWorld(res) {
        res.send("Hello world!");
    }
    
    exports.api = functions.https.onRequest(app);

    当只提供功能时,这与预期一样有效。

    但是,当我运行firebase Service时,重写(如下所示)仍然无法用于我希望重写到函数的api路由:

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

    我怀疑在运行firebase Service时,它实际上并没有为这些函数提供服务,因为我没有在终端中列出任何端点。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Paul Renshaw    8 年前

    我以以下内容为例,使一切都按预期进行:

    函数/src/索引。ts

    import * as functions from 'firebase-functions';
    import * as express from 'express';
    
    const app = express();
    
    app.get("/:function", (req, res) => {
        switch(req.params.function) {
    
            case 
                "helloWorld" : helloWorld(res)
                break;
    
            default : res.send("Invalid function requested.")
    
        }
    });
    
    app.get("/users/:id", (req, res) => {
        res.send("User with ID: " + req.params.id)
    });
    
    function helloWorld(res) {
        res.send("Hello world!");
    }
    
    exports.api = functions.https.onRequest(app);

    firebase。json(重定向和重写)

        "redirects": [
          {
            "source": "/",
            "destination": "/app/",
            "type": 301
          }
        ],
        "rewrites": [
          {
            "source": "/app/**",
            "destination": "/app/index.html"
          },
          {
            "source": "/**",
            "function": "api"
          }
        ]