Get in touch
or send us a question?
CONTACT

[Node.js Tutorials for Beginners] – Unit 9: Express framework part 1

Table of Contents

1. What is Express?

2. Why use Express?

2. Installing & using Express

3. Demo: Creating a simple Rest api

1. What is Express?

It’s a web framework that let’s you structure a web application to handle multiple different http requests at a specific url.

Express is a minimal, open source and flexible Node.js web app framework designed to make developing websites, web apps, & API’s much easier.

2. Why use Express?

Express helps you respond to requests with route support so that you may write responses to specific URLs

Supports multiple templating engines to simplify generating HTML.

The nice thing about it is it’s very simple and it’s open-source

3. Installing & using Express

You can get it through NPM

npm install express

4. Demo: Creating a simple Rest api

A router maps HTTP requests to a callback

HTTP requests can be sent as GET/POST/PUT/DELETE, etc..

URLs describe the location targeted

Basic express app:

var express = require(‘express’);

var app = express();

app.get(‘/’, function(req, res){

res.send(‘Hello World’)

})

var server = app.listen(8081, function(){

var host = server.address().address

var port = server.address().port

console.log(‘Example app listening’, host, port)

})

Line 1: You can think of require as a need to import something. You can instantiate it at the top of your file.

Line 2: We are creating the express app by setting it to the app variable.

Line 3: .get is saying that when it gets that route it should give the response that is specified in the function. It takes in 2 arguments: (1) the url (2) the function that tells express what to send back to the person making the request.

Line 5: .listen is going to bind the application to the port on our machine.

Now run the unit9.js to see the result:

$ node unit9.js

Go to your browser and go to port 8081, you should see “Hello Express”:

Thank you for reading!