Repository: Ionic App Repository Github
Software Requirements:
Visual Studio Code(Or any preferred code editor)
Chrome(Or any preferred browser)
What you will learn:
In this tutorial you would learn how to live code a real ionic application with practical examples including these major concepts:
Difficulty: Intermediate
Tutorial
So in today's tutorial we would be dealing with how we can make a simple back-end for our application and host in on a server so we can collect data across multiple devices.
For this back-end restAPI we would be using express and for our database we would be using MongoDb.
So what is express?
Express is a framework that helps us create a simple back-end API's for our application.
How about MongoDb?
MongoDb is a storage platform that helps you store files in a more concise and accessible form for your database. For this tutorial, you could use a simple free account. Just head to the website here.
So before we make and understand a simple back-end REST API, let's understand how to send HTTP requests through ionic directly. For this we would use something we call the httpclientmodule.
To use this head to your app.module.ts and add this module to your imports and also to your providers. After that this is how our file would look.
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { IonicStorageModule } from '@ionic/storage';
import { httpClientModule } from '@angular/common/http';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { ProductsPage } from '../pages/products/products';
import { NewproductPage } from '../pages/newproduct/newproduct';
import { CheckoutPage } from '../pages/checkout/checkout';
import { ProductdetailPage } from '../pages/productdetail/productdetail';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
ProductsPage,
NewproductPage,
CheckoutPage,
ProductdetailPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
ProductsPage,
NewproductPage,
CheckoutPage,
ProductdetailPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
httpClientModile
]
})
export class AppModule {}
So after this we would need to create a service for our application.
Why services?
We make http requests through services so that we could easily make the same http request over various pages without having to rewrite code for each page. Through this services we can make functions that make calls to our apis and serve this calls to all our pages.
Lets do this then
Our cli has an inbuilt function to generate a service provider so simply head to your terminal and type
ionic g service store
This would compile and give you a directory which looks just like this.
provider/store/store.ts
So now we go on to setting up a simple backend
Start by running this command
npm install --save express mongodb@2.2.16 body-parser nodemon
After this you can create a file called
ourserver.js
start up by requiring the basic files for this server and creating a port to listen for our app through
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
app.listen(port, () => {
console.log('We are live on ' + port);
});
Now we would try to seperate the components of our app into folders that would hold routes for the server.
This is not too useful for a small app but would be generally more useful in an application that is larger, so that we would have a more organized view.
So now we create a folder within our directory called app and in it add another folder called routes. In this folder add two files called index.js and node_modules.js
Then open our node_modules file and add the following
module.exports function(app, db) {//setting up one of our routes
and then in our index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
We can then import these files into our main file
The file should look like this
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
Okay so we've succesfully set up the routes. Time to handle our requests.
We will start with a post request. In ionic to call this request with the client module, we could simply import the httpClientModule and then within our service run
this.http.post(localhost:8000)//Because this is the development port we're running this on
So before we get to that lets see how the server side will deal with that request
In our node_routes.js
Add this
module.exports = function(app, db) {
app.post('/create', (req, res) => {
//This is where we create a file to add to our database
res.send('Hello')
});
};
The function above deals with post request that are made to localhost:8000/create. This means that if we send a http post request to that exact file, express will run this piece of code.
So we'll test this code out using an app called postman
You can get this application here
This application helps us simulate these request to see how they'll respond if they were hosted in our domain name on a web host.
So for now this is the response we would have
This shows that our backend is ready for requests.
For this backend we wouldn't like to just send raw data over the internet but we would want to encode it. The problem with this is that express cannot read url-encoded data so we would need to use something else.
And that is why we installed body parser to our application and are using it as a dependency.
We would like to add this body parser to our server.js, so after all our require files, add this
app.use(bodyParser.urlencoded({ extended: true }));
We can then send a simple encoded request through postman and see how our console will log it out
So the last thing for this tutorial would be trying this our through our ionic app.
We have a simple test backend running, but we would like to see how our ionic app would interact with it.
Head to the store.js file we created and make a http request to our localhost like this
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class StoreProvider {
constructor(public http: HttpClient) {
console.log('Hello StoreProvider Provider');
}
sendRequest(){
this.http.post('localhost:8000/create').then(res){
console.log(res)
}
}
So try this out and if you're having any problems, leave it in the comment section. We'll continue adding our database in the next tutorial.