Firebase functions: koa.js server how to deploy

2019-07-19 16:39发布

I already have an app written in MERN stack with koa server prepared build version. My main node file to run by node server.js command to start the whole app looks like this.

In every tutorial, I see that I need to add functions.https.request etc. in the beginning of coding (or at least to suppose doing it). How could I host my app on firebase the same as I could on heroku - with whole server side?

4条回答
迷人小祖宗
2楼-- · 2019-07-19 16:52

You can run an express application using firebase hosting to serve dynamic content via firebase functions. You cannot, however, use Koa.js currently. The functions.https.onRequest requires you to pass an HTTP request handler or an express app returned from express().

Here is the relevant article from Firebase about serving dynamic content from functions. https://firebase.google.com/docs/hosting/functions

Here is a video tutorial from Firebase on using express. https://www.youtube.com/watch?v=LOeioOKUKI8

查看更多
萌系小妹纸
3楼-- · 2019-07-19 16:52

You can actually skip the listen call entirely, and use app.callback(). This seems to make more sense than listening on a random port that never actually gets hit.

const functions = require('firebase-functions');
const app = new Koa();
... // set up your koa app however you normally would
app.use(router.routes());
module.exports.api = functions.https.onRequest(app.callback());
查看更多
一纸荒年 Trace。
4楼-- · 2019-07-19 16:59

You can't deploy and run an arbitrary node app on Cloud Functions. You have to make use of the different types of triggers that are defined by the product.

See the Cloud Functions for Firebase main page to see the list.

  • Cloud Firestore Triggers
  • Realtime Database Triggers
  • Firebase Authentication Triggers
  • Google Analytics for Firebase Triggers
  • Crashlytics Triggers
  • Cloud Storage Triggers
  • Cloud Pub/Sub Triggers
  • HTTP Triggers
查看更多
爷的心禁止访问
5楼-- · 2019-07-19 17:14

Actual, it is possible to host Koa app using firebase functions, I figure it out after some heavy Googling and analyzing.

This is a piece of code from my project, it is now hosted with firebase functions:

const Koa = require('koa');
const app = new Koa();

// ... routes code here ...

const server = app.listen(config.port, () => {
  console.log(`HITMers-server is running on port ${config.port}`);
});

// This is just for running Koa and testing on local machine
module.exports = server;

exports.api = functions.https.onRequest(app.callback());

You can see the docs and tutorial video for more information.

By the way, here is another example to deploy Koa to now.sh version 2.

查看更多
登录 后发表回答