How to run Node.js server in Ionic mobile app?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m currently #1 in the top All time answerers list.

I answered this question by user Shubham:

I am making an app using MEAN and ionic framework where nodejs is a middleware to connect to the database(mongoDb). I need to run the nodejs server using node server.js and the app using ionic serve. This is my server.js.

var express          = require('express'),
app              = express(),
bodyParser       = require('body-parser'),
mongoose         = require('mongoose'),
CohortController =require('./www/server/controller/CohortController');

mongoose.connect('mongodb://localhost:27017/persistent');

app.use(bodyParser());

app.get('/api/cohorts',CohortController.list);
app.post('/api/cohorts',CohortController.create);

app.listen(3000,function(){
console.log('Listening...');
})

Now this is my app.js. I use http://localhost:3000 to get the JSON.

app.controller('CohortController',['$scope','$resource',
  function($scope,$resource){
    var Cohort=$resource('http://localhost:3000/api/cohorts');
    Cohort.query(function(results){
      $scope.cohorts=results;
    });
    $scope.cohorts=[];

    $scope.createCohort= function () {
      var cohort=new Cohort();
      cohort.name=$scope.CohortName;
      cohort.id=$scope.CohortId;
      cohort.$save(function(result){
        $scope.cohorts.push(result);
        $scope.CohortName='';
        $scope.CohortId='';
      });
    }
  }]);

How can I run the node server when I convert it into a mobile application? How the application will use the API?

My answer was:

You will have to have your Node.js app running on a server which you would then access (from your Ionic app) via it’s public IP. So, you wouldn’t use http://localhost:3000 to get the JSON, instead you would use something like http://123.456.789.123:3000.

But, usually, this is not the way you would do it (with the port 3000). What you would additionally do is put (for example) Nginx in front of your Node.js app (see an example here) in order to serve your api from the standard HTTP port (80).

So, basically, you can’t actually “run Node.js server in Ionic app” – the way you do it is run the Node.js app separate from Ionic and expose its functionality via a standardized API (usually these days RESTis what you would want to achieve) which you then “consume” via Ionic’s (well, to be exact, it’s actually Angular’s) $resource module.

Hope this helps clear things up a bit.

Written by Nikola Brežnjak