how to handle root path request with node.js on firebase hosting?

左心房为你撑大大i 提交于 2020-03-25 08:45:23

问题


I'm developing web system using firebase hosting + functions. Inspite of specifying rewrite rules on firebase.json, a part of routing doesn't work.

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.

This is my firebase.json

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

And this is node.js code.

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

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

result

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

Do you know how to handle root path request with node.js on firebase hosting.


回答1:


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

Priority order of Hosting responses

The different Firebase Hosting configuration options described on this page can sometimes overlap. If there is a conflict, Hosting determines its response using the following priority order:

  1. Reserved namespaces that begin with a /__/* path segment
  2. Configured redirects
  3. Exact-match static content
  4. Configured rewrites
  5. Custom 404 page
  6. Default 404 page

Exact-match static content is high priority order than Configured rewrites.

So https://myurl/ get static content /index.html.

Can you try remove public/index.html?


I tried. I can rewrite.

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

And you should check https://firebase.google.com/docs/hosting/functions .




回答2:


  1. Make a dummy folder that is empty. eg.: dummyApiFolder
  2. Make a very simple cloud function. eg.
exports.bla = functions.https.onRequest(async (req, res) => {
    res.send("server bla");
});
  1. Use the following hosting rules
    "hosting": {
        "target": "api",
        "public": "dummyApiFolder",
        "rewrites": [
            {
                "source": "**",
                "function": "bla"
            }
        ]
    }

3.1. target is only needed if you have set this up in your .firebaserc file

3.2. "public": "dummyApiFolder", is needed. Otherwise the CLI won't allow the deployment

Now all requests should get forwarded to bla.

The reason I'm advising to start with a simple cloud function is, express can be setup incorrectly. This can also give you an error, but you end up not knowing if it's a firebase issue or a code issue!



来源:https://stackoverflow.com/questions/56272803/how-to-handle-root-path-request-with-node-js-on-firebase-hosting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!