Reputation: 247
I'm pretty new with NodeJs and Firebase. Currently, I have a NodeJs project with Express and the following file structure:
` + /root
+ /db
- user.js
+ /domain
- user.js
+ /node_modules
- ...
+ /routes
- routes.js
- sever.js
- config.json`
I want to host this on Firebase but it adds me the files index.html and others. If I try with Cloud functions it adds me /functions and inside this an 'index.js' file, like this:
` + /root
+ /db
- user.js
+ /domain
- user.js
+ /functions
- index.js
+ /node_modules
- ...
+ /routes
- routes.js
- sever.js
- config.json
-firebase.json`
I'd try to paste my server.js code inside the index.js but I get errors from references and missing packages.
This is my index.js code:
const functions = require('firebase-functions');
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
// Use bodyParser to parse the parameters
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json({limit: '10mb'}));
// Call the routes
require('../routes/routes')(app);
exports.api = functions.https.onRequest(app);
And my routes.js code:
var userRoute = require('./users');
//Register routes and link to functions
module.exports = function(app){
app.post('/register', user.userRoute);
}
My firebase.json
{
"hosting" : {
"public" : "public",
"rewrites" : [{
"source" : "/",
"function" : "api"
}]
}
}
When I run local through
firebase serve --only functions
works perfect but the problem comes where I try to deploy Any idea?
Upvotes: 6
Views: 10307
Reputation: 18595
There are a few niche cases to do this. Provided you must do this, it is possible. It's documented at Serve Dynamic Content with Cloud Functions.
Basically, you configure a redirect in Firebase Hosting via your firebase.json. Something like below:
"rewrites": [ {
"source": "/myapi", "function": "myapi"
} ],
Then, you configure your index.js
file in Firebase Functions to listen for HTTP requests at that path, like:
app.get("/myapi", (request, response) => {
response.set("Cache-Control", "public, max-age=300, s-max-age=2629746");
var myparam = request.query.item;
return fetchSomethingFromFirestore(myparam).then((resp) => {
return response.render("template", {
myProperty: resp.valueForPugTemplate
});
});
});
app.use(function(err, req, res, next) {
return errorhandler(err, req, res, next);
});
const myapi = functions.https.onRequest((request, response) => {
if (!request.path) {
request.url = `/${request.url}`;
}
return app(request, response);
});
module.exports = {
myapi,
};
Upvotes: 5