简体   繁体   中英

Express.js: How to get 'Clean Path' when using app.use() with RegEx path pattern in Firebase Functions?

My goal: When the browser URL is http://localhost:5000/register , I just want Express to return /register , that's all. But it seems like such simple goal cannot be easily achieved with Express .

First of all, I think it's good to show you my firebase.json before proceed:

firebase.json:

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

Then in my Firebase Functions, 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);

Below are the console results:

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 = /

As you can see, none of the above can help to achieve my simple goal except having so many variations with similar results, eg / . Is there any other reliable option that I can use just to get /register without dangerously manipulating /firebase-project-id/us-central1/site/register string? Many thanks!

In reference to @Doug Stevenson's post here , req.headers['x-original-url'] works!

Console output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM