【问题标题】:how to handle root path request with node.js on firebase hosting?如何在firebase托管上使用node.js处理根路径请求?
【发布时间】:2019-10-09 21:15:03
【问题描述】:

我正在使用 Firebase 托管 + 功能开发网络系统。 尽管在 firebase.json 上指定了重写规则, 部分路由不起作用。

root/
 ├ functions/
 │  ├index.js
 │  ├routes/
 │  │  └ index.js
 │  └views/
 │    ├ index.jade
 │    └ sub.jade
 └ public/
    └index.html // this is created by default. I don't want to use this.

这是我的 firebase.json

"rewrites": [{
      "source": "**",
      "function": "app"
    }],

这是 node.js 代码。

router.get('/', function(req, res, next) {
    res.render('index');
});

router.get('/subdir', function(req, res, next) {
    res.render('sub');
});

结果

https://myurl/ -> public/index.html is shown.(not handled on node.js)
https://myurl/ -> handled on node.js

你知道如何在 firebase 主机上使用 node.js 处理根路径请求吗?

【问题讨论】:

    标签: firebase google-cloud-functions firebase-hosting


    【解决方案1】:

    https://firebase.google.com/docs/hosting/full-config#hosting_priority_order

    托管响应的优先顺序

    此页面上描述的不同 Firebase 托管配置选项有时可能会重叠。如果存在冲突,Hosting 将使用以下优先级顺序确定其响应:

    1. 以 /__/* 路径段开头的保留命名空间
    2. 配置的重定向
    3. 完全匹配静态内容
    4. 配置重写
    5. 自定义 404 页面
    6. 默认 404 页面

    完全匹配静态内容的优先级高于配置的重写。

    所以https://myurl/ 获取静态内容/index.html

    您可以尝试删除 public/index.html 吗?


    我试过了。我可以重写。

    https://github.com/zkohi/firebase-hosting-using-functions-samples

    你应该检查https://firebase.google.com/docs/hosting/functions

    【讨论】:

    • 再试一次就成功了。我不知道为什么结果与上次不同,但它仍然有效。谢谢
    【解决方案2】:
    1. 创建一个的虚拟文件夹。例如:dummyApiFolder
    2. 制作一个非常简单的云函数。例如。
    exports.bla = functions.https.onRequest(async (req, res) => {
        res.send("server bla");
    });
    
    1. 使用以下托管规则
        "hosting": {
            "target": "api",
            "public": "dummyApiFolder",
            "rewrites": [
                {
                    "source": "**",
                    "function": "bla"
                }
            ]
        }
    

    3.1。 target 仅在您已在 .firebaserc 文件中设置时才需要

    3.2。需要"public": "dummyApiFolder",。否则 CLI 将不允许部署

    现在应该将所有请求转发到bla

    我建议从简单的云功能开始的原因是,express 可能设置不正确。这也可能会给您一个错误,但您最终不知道这是火力基础问题还是代码问题!

    【讨论】:

      【解决方案3】:

      很简单!只需将公共目录中的index.html 文件重命名为其他名称即可。另外,以防万一:在firebase.json 文件中,更改public 属性的值 从public.

      【讨论】:

        猜你喜欢
        • 2017-10-30
        • 2013-02-28
        • 2020-04-29
        • 2021-01-06
        • 2020-07-05
        • 1970-01-01
        • 2020-01-25
        • 2015-03-02
        • 2013-03-03
        相关资源
        最近更新 更多