4.1 REST back-end in Node

  • Posted on: 9 August 2018
  • By: Ryoma Ohira
2.1 Angular Workshop

1. Introduction to REST

REST is short for REpresentational State Transfer and is a style of system architecture for communicating between systems on the internet. Compliant systems are called RESTful systems and separate the concerns between client and server systems. It's known as being a 'stateless' architecture in that the client and server are unconcerned with the states of the other. An example is when you make a search query, your browser sends a message to the server requesting results with a key word and search parameters. When the server receives a message, it will run some processes and then return a web page with the results of the query. It then doesn't really care what your browser does until it makes the next request (maybe the next page of results). 

In this tutorial, we'll be creating a Node server that uses Express in order to serve an Angular application. 

1. Setting Up Express

Let's get started! I'm going to assume you have NodeJS installed and you're using your favourite IDE to develop. Make sure you've already created a folder for your project to start from.

1.1 Create a new Node project

Make sure you're in your project folder in terminal and initiate a new Node project

npm init

Npm will ask you for a few details - feel free to answer the questions or leave them as default. It's up to you. 

1.2 Install Express

We're goign to be using Express so we might as well start by installing the module.

npm install express --save

You can use the short form of install as i. --save will make sure that the module is saved as a dependencity in your project json file. 

1.3 Set Up Express

Now we can create a server.js file and add Express to our project.

// server.js
const express = require('express');

This adds the Express module into a constant called express. From here, we can instantiate an application using

// server.js
const app = express();

I also want to create some data that can be served. Let's create some students

// server.js
var students = [
  { id: 1, name: "James", gpa: 5 },
  { id: 2, name: "John", gpa: 5.3 },
  { id: 3, name: "Jane", gpa: 5.6 },
  { id: 4, name: "Mary", gpa: 6.2 }

and then start the server  with

// server.js
app.listen(8000, function(){
    console.log('Server running');

This will host the server on localhost or using port 8000. A callback function is passed so that once the server is successfully started, we get a message on our terminal letting us know.

1.4 Running the Server

Now to run the server, you can type the following command in terminal

node server.js

alternatively, we can also use

npm start


We need to create some end-points for serving things. Lets define our API end-points to all point to an "api" route. This way we can have a dedicated "channel" for serving APIs but also means we can serve other things on other "channels". 

2.1 Creating Students Routes

Create the first route you want for your API end-points. We'll be using Express and its route-method to do this. 

// server.js
app.route('/api/students').get(function(req, res){
   //call back

In the callback method, we can decide what we want to do, lets respond with an array of JSON objects.

// server.js
app.get('/', function (req, res) {
app.get('/api/students', function(req, res){
        students: [{name:'John'}, {name:'Jane'}]

We should be familiar with get at this point, but what does it do? GET is a common HTTP method where a query string is set in the URL of the request. You can see this when you do a search in Google, you will see a new string added to the end of your URL after a question mark (?). Systems can transfer information between each other using this GET method. Remember when we mentioned that REST is stateless? GET is a way of letting the server know the current state of the client when sending a message.

2.2 Student Route

At the moment, if we request on our /api/students route, we will be given a list of students. What if we want to access a single student? We can create a new route for that too.

// server.js
app.route('/api/students/:name').get(function(req, res){
    const requestedStudent = req.params['name'];
    res.send({name: requestedStudent});

Here we can create another end point where if we go to /api/students/John, we will get a JSON object containing the student's name as a response. 

3.1 Objects and End-points

We can also create objects at end points. If you want to send a post request to the server, say through a form, we can send a new object to the server. However, to do this, we need to install another module called body-parser. Do this in terminal

npm install body-parser --save

Body-parser used to be part of Express core but got removed from Express 4 onwards. We can then add this to our server.js with:

// server
const bodyParser = require('body-parser');
app.route('/api/students').post(function(req, res){
    res.send(201, req.body);

Notice that our send() response function is now using two parameters instead of one? The first paramter is a HTTP-status code and is standardised. By default, send() will send a status code of 200 which indicates "successful". In this case we're using 201 for "created". 

4. CORS Middle Ware

CORS is Cross Origin Resource Sharing and enables a HTTP-request to a top-level domain that is different from current domain the browser is at. For example, if you're on this server and it makes a request to Facebook or Instagram, we're making a CORS request. Single-page websites will commony make requests to other servers that are not hosted under the same domain as the Angular app so we'll be enabling CORS. To do so, we have to enable from specific domains. Start by installing CORS

npm install cors --save

Then add the CORS module to your project and make sure your app uses it

// server.js
const cors = require('cors');

var corsOptions = {
    origin: 'http://localhost:4200',
    optionSuccessStatus: 200


CORS will act as middleware and will intercept all requests and add the required CORS headers to the responses. Without this, you may get some errors on Chrome and Firefox on your console about CORS not being enabled. 

5. Final Thoughts

After saving you can then run your node server. At this point, we can access our API server by going to the URL that your node server is hosted on. 

Category Terms: 
Tutorial Weight: