【问题标题】:Express.js: How to get 'Clean Path' when using app.use() with RegEx path pattern in Firebase Functions?Express.js:如何在 Firebase 函数中将 app.use() 与 RegEx 路径模式一起使用时获得“干净路径”?
【发布时间】:2020-10-02 03:02:46
【问题描述】:

我的目标:当浏览器URL为http://localhost:5000/register时,我只想让Express返回/register,仅此而已。但是,Express 似乎无法轻松实现如此简单的目标。

首先,我认为在继续之前向您展示我的firebase.json 会很好:

firebase.json:

"hosting": 
    {
      "target": "store",
      "public": "store/public",
      "ignore": [
        "firebase.json",
        "**/.*",
        "**/node_modules/**"
      ],
      "rewrites": [
        {
          "source": "/app{,/**}",
          "destination": "/app/app.html"
        },
        {
          "source": "**",
          "function": "site"
        }
      ]
    }

然后在我的 Firebase 函数中,index.js:

const functions = require('firebase-functions');
const express = require("express");
const site = express();

// Any path except /app/anything.
site.use(/^\/(?!app).*/, function (req, res, next) {
    console.log(`req.path] = ${req.path}`);
    console.log(`req.route.path] = ${req.route.path}`);
    console.log(`req.originalUrl] = ${req.originalUrl}`);
    console.log(`req.url] = ${req.url}`);
    console.log(`req.baseUrl] = ${req.baseUrl}`);
    console.log(`site.mountpath = ${site.mountpath}`);

    next();
});

site.get("/", (req, res) => {
    res.send("Homepage");
});

site.get("/register", (req, res) => {
    res.send("Registration Page");
});

exports.site = functions.https.onRequest(site);

以下是控制台结果:

i  functions: Beginning execution of "site"
>  req.path] = /
>  req.route.path] = *
>  req.originalUrl] = /firebase-project-id/us-central1/site/register
>  req.url] = /
>  req.baseUrl] = /firebase-project-id/us-central1/site/register
>  site.mountpath = /

如您所见,上述任何一项都无法帮助实现我的简单目标,除非有这么多具有​​相似结果的变体,例如/。有没有其他可靠的选项可以用来获取/register 而不会危险地操纵/firebase-project-id/us-central1/site/register 字符串?非常感谢!

【问题讨论】:

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


    【解决方案1】:

    参考@Doug Stevenson's post here,req.headers['x-original-url'] 有效!

    控制台输出:

    req.headers['x-original-url'] = /register
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多