问题
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:
- Reserved namespaces that begin with a /__/* path segment
- Configured redirects
- Exact-match static content
- Configured rewrites
- Custom 404 page
- 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:
- Make a dummy folder that is empty. eg.:
dummyApiFolder - Make a very simple cloud function. eg.
exports.bla = functions.https.onRequest(async (req, res) => {
res.send("server bla");
});
- 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