Lessons 234, 235 & 236 – Complete 2020 Web Development Bootcamp

Lesson 234 – What is Express?

Express is node.js framework.

It was built to help you write less repetitive code when building web applications.

Lesson 235 – Creating Our First Server with Express

The first step is to use the terminal to create a new folder labelled “my-express-server in the Desktop folder.

//to get into the Desktop folder
cd Desktop/

//to make a new folder labelled "my-express-server"
mkdir my-express-server

//to create a new "server.js" file in the "my-express-server" folder
touch server.js

Once this has been done, you then cd into the “my-express-server” and initialize npm.

cd my-express-server

npm init

You then fill in the description and author name details. Once this has been done a “package.json” file is created in the “my-express-server” file.

The next step is to install Express. To do that in the terminal you type –

npm install express

The next step is to require express in the server.js file like this –

const express = require("express");

The next step is to create a new const called “app”.

const app = express();

Then you use the app to listen on a specific port for any http requests that get sent to our server.

app.listen(3000);

To see when the port is set up and the server is running you can add a callback function to the listen method.

app.listen(3000, function() {
  console.log("Server started on Port 3000.");
});

Lesson 236 – Handling Requests & Responses – the GET request

Right now if you got to your browser and input “localhost: 3000” you will get this error message – “Cannot GET /”.

To stop this error we have to add code which will cause our server to send back information when the browser makes the GET request.

To do that, you insert in the server.js file right above this code –

app.listen(3000, function() {
  console.log("Server started on Port 3000.");
});

the following new code –

app.get("/", function(req, res){
   response.send("<h1>Hello World!</h1>");
});

The “app.get” method in the above example is listing on the home page for a GET request. When it receives the GET request it calls the anonymous function and using the response.send method, sends the response “Hello World!” styled as a h1 heading. This h1 heading “Hello World!” is displayed on the home page on the website user’s browser.