Using Express and API Data
Upon completion of this mini-project, you would be able to:
Install Express server
Install Axios http client
Consume web APIs using Axios http client for our back-end web application
Consume data API using Angular HttpClient for our front-end web application
1. Project 9a – Part 1 Back-end
In this project you will develop an Angular web app, called meanApp and a back-end project which run Express, a backend Node.js framework. We will also look into using Angular HttpClient to consume our back-end API and retrieve the data for display purpose.
For this exercise, we will be creating the back-end application inside our Angular project folder to simplified coding. Note: In a real-world application, front-end and back-end applications are usually in different projects and they will most likely reside in different server.
For Part 1 of this exercise, we will be focusing on setting up our back-end server.
Creating the Angular Project
Go to Windows Start Menu à Command Prompt.
Navigate into the previously created folder angular-apps:
cd angular-apps
To start a new project called meanApp, type in the following into the command prompt windows:
ng new meanApp
Open Visual Studio Code, Select File > Open Folder (Crtl + K, Crtl + O) and open up the meanApp project
Select Terminal > New Terminal (Crtl + Shift + `) and press enter to open up the terminal (command prompt) inside Visual Studio Code.
Install Express
To install express for this project, go into the directory of the meanApp project by typing the following:
cd meanApp
Then, to install Express type in the following into the command prompt windows:
npm install express body-parser --save
This will automatically install the Express server packages into the meanApp project.
Install Axios
To retrieve and display API data in our back-end system using Express, we use Axios, which is a promise-based HTTP client for the browser.
Then, to install Axios type in the following into the command prompt windows:
npm install axios --save
This will automatically install the Axios packages into the meanApp project.
Create the /server folder and server.js file
For Node server, you need to create a /server folder. Go into the meanApp project directory and type the following in your terminal to create the server folder:
md server
Navigate to the /server folder and Select File > New File (Crtl + N) to create a new file inside
The file is blank by default. In this file we want to configure the default server.js file needed to run our back-end server. Paste the following codes inside:
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const cors = require('cors');
// Get our API routes
const api = require('./routes/api');
const app = express();
//Prevent Cross-origin request to be blocked
app.use(cors());
// Parsers for POST data
app.use(express.json());
// Point static path to dist
app.use(express.static(path.join(__dirname, '../dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/meanApp/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
Save the file as server.js in “/meanApp/server” folder
Create the /server/routes folder and api.js file
For Express server, you need to also create a /server/routes folder. Navigate into the newly created /server directory by typing the following:
cd server
Then, type in the following to create the /routes folder:
md routes
Select File > New File (Crtl + N)
The file is blank by default. In this file we want to create the api.js file that links to the mock API data needed to run on Express. Paste the following codes inside:
const express = require('express');
const router = express.Router();
// declare axios for making http requests
const axios = require('axios');
const API = 'https://jsonplaceholder.typicode.com';
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
// Get all posts
router.get('/posts', (req, res) => {
// Get posts from the mock api
// This should ideally be replaced with a service that connects to MongoDB
axios.get(`${API}/posts`)
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Save the file as api.js in the “/server/routes” folder.
Once you have completed the steps above, your meanApp project folder structure should look like this:
Run the app using Express
To run the app using Express, we need to build the app. Building the app will auto-create the back-end application inside the /dist folder.
Note: Whenever there are code changes in your back-end application, you have to rebuild your application using the ng build command.
Ensure that you are in the server folder; if you are not inside, you can use the cd command to change to the folder to where the server.js file exists.
Type the following into the command prompt window:
ng build
It will take some time for the build to be completed, wait for a few minutes.
After the build is done, you can run the app, by typing in the following into the command prompt window:
node server.js
It will show the following message to indicate it is running:
Open Google Chrome browser and type in:
You will see the following displayed on the browser:
If you type the following in the browser
Then, you will see the following displayed on the browser: (this is the JSON data)
Recap on what we have done
Create a web application call meanApp
Install Express and Axios into our project.
Create and configure server.js in order to run our back-end application.
Create and configure api.js to:
- Declare Axois for making http requests
- Setup the default API route “/api/”
- Setup the API route “/api/posts”
- Call the mock data API URI https://jsonplaceholder.typicode.com using Axois
We have successfully setup our nodejs back-end web server. Take some time to review the api.js file to see what the lines are where they perform the functions as stated above
2. Project 9a – Part 2 Front-End
In the previous part, we had created our back-end application using node.js and express framework. For the next part the exercise, we will be focusing on consuming our back-end application APIs using Angular httpClient.
Generate a Service - posts
To end the application, enter the Ctrl + C in your terminal
Navigate to meanApp root directory: /meanApp. (Hint: you can do so using the cd .. command)
In the terminal, type in the following to generate a service:
ng generate service posts
This will auto-create two service files for the web app in the folder under \src\app. The main file we need is posts.service.ts.
Edit the posts service – posts.service.ts
Open the file posts.service.ts
Here we will be implementing the following:
- Import the HttpClient libraries
- Inject the HttpClient into our posts service constructor
- Create a getAllPosts() function that perform a Http GET request to api url: /api/posts
Update the Typescript file as follows (changes highlighted in yellow):
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostsService {
url:string = "http://localhost:3000/api/posts";
constructor(private http:HttpClient) { }
getAllPosts() {
return this.http.get<any[]>(this.url);
}
}
Edit the Typescript file – app.module.ts
Open the file app.module.ts
Here we need to include the HttpClientModule and PostsService in the root app module. By importing our services and the HttpClientModule into the root module, we enables them to be injected into different components and sharing of the same instance of the service.
Update the Typescript file as follows (changes highlighted in yellow):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { PostsService } from './posts.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [PostsService],
bootstrap: [AppComponent]
})
export class AppModule { }
Edit the Typescript file – app.component.ts
Open the file app.component.ts
Here we will be injecting the PostsService and invoking the getAllPosts() function inside the constructor. This will help us to retrieve the posts when our component is first created.
Update the Typescript file as follows (changes highlighted in yellow):
import { Component } from '@angular/core';
import { PostsService } from './posts.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'List of Posts';
posts: any = [];
constructor(private postsService: PostsService) {
this.postsService.getAllPosts().subscribe(posts => {
this.posts = posts;
});
}
}
Edit the HTML file – app.component.html
Open the file app.component.html
Overwrite the file with the following code:
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
</div>
<div class="container">
<div class="row" *ngFor="let post of posts">
<div class="card card-block">
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text">{{post.body}}</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
Build and Run the Back-end Application
To run our back-end application using Express, we need to re-build the app.
So, type in the following into the command prompt window:
ng build
Then, run the server by typing in the following (check that you are in the same location as server.js before executing the command):
node server.js
Run the Front-end Application
To run the app, open up another command prompt window and type in the following: (Note that you should open another terminal and not close the previous terminal used to start the web server or it will close the web server)
ng serve
A lot of messages will appear. Wait for the message ‘Compiled successfully’ line to appear. It will take several minutes. Once this appears it means the app is running.
Open Google Chrome browser and type in:
Then, you should see the following window:
Recap on what we have done
Create a posts service and create a function getAllPosts to peform a HTTP GET request to our back-end web server route “/api/posts” using Angular HttpClient.
Import the HttpClient Modules and Posts Service into the app module to enable sharing of the services.
Inject the Posts Service into App Component and invoke the getAllPosts function in the constructor in order to retrieve the posts when our component is first created.
Edit the App Component HTML to display the data retrieved from the getAllPosts function.
Think about what you have learnt previously in CDEV/DBAV:
Can you map the components for CDEV/DBAV with FWEB code?
Can you identify which components are front-end and which components are back-end for this project?
References:
In this lesson, you have successfully:
Install Express server
Install Axios http client
Consume web APIs using Axios http client for our back-end web application
Consume data API using Angular HttpClient for our front-end web application
In the next lesson we will be exploring integrating MongoDB with our back-end application.
To get any support related to MEAN STACK OR MERN STACK you can send your requirement details at:
realcode4you@gmail.com
Comments