Shubham Pendharkar
Shubham Pendharkar

Reputation: 330

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

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?

Upvotes: 5

Views: 11234

Answers (1)

Nikola
Nikola

Reputation: 15038

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 REST is 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.

Upvotes: 5

Related Questions