Getting Started With Express

Express.js, or simply Express, is a web application framework for Node.js, released as free and open-source software under the MIT License.

In last weeks post I went over what the MERN stack is. Today we will begin development by creating our backend which will be written in Express.

If I were to give a brief overview of what Express is, I would summarize it as a framework in Node.Js that allows an easier way to define our routes as opposed to writing and defining our routes in Node.JS itself.

To get started let’s create an empty directory and in terminal we will want to be inside this directory. We will then run the command npm init which will create the package.jsonamongst other files. After we do this we will need to install the express package. To do this we will need to run the command npm install express --save One more package we should install now is nodeman which I will talk about later, to do this lets do npm install nodemon .

In summary so far we should do the following:

  1. npm init
  2. npm install express
  3. npm install nodemon

Now we can start our Express project. Let’s now start by creating a folder called src within out express folder. This will hold all of our files pertaining to our backend ie our Models, Routes, and Controllers. Here we should create a file called index.js where it should contain the following:

// load express module which returns a function
const express = require('express')
//express return value is object of type express
const app = express()
const port = process.env.PORT || 3000
app.listen(port, ()=> console.log(`Listen on ${port}`))

The following lines are considered the boiler plate in order to get the app up and running. With this created all thats left to see if it is working is to create our routes.

In HTML there are 5 verbs.

  1. POST- creates a new resource
  2. PUT- modify the collection itself
  3. GET-returns a list of resources or a single resource
  4. PATCH- replaces every resource in this collection
  5. DELETE-removes the collection

These verbs can be seen when we define our routes in Express see below for how we define our routes in Express:

app.get()
app.post()
app.put()
app.delete()

For this guide we will be focusing on GET requests to create a simple web page. A GET request takes two arguments, it takes the path or url, and a callback function.

The call back function is called when the get request to the endpoint is made. This callback function should take 2 arguments. It should take the request and the response. Putting all this information together we can make a simple get request to our root view "/" by doing the following in the index.js.

 app.get("/",(req, resp)=> {
 resp.send("Hello World!!!")
 })

So now we are going to run our Express Server. In terminal we will do nodemon src/index.js. The reason we will be using nodemon is because if we run node we will have to keep restarting our server. With nodemon our server will always monitor our changes and update accordingly. Now if we go to the browser and visit you should see the resp.send message we have created.

So now that we have our root directory defined, lets create a route that will give us a list of people to be as follows:

app.get("/people",(req, resp)=> {
 resp.send(["bob","jim","joe"])
 })

If we visit "/people" we should get an array with those names. Let’s take this a step further and define a route with param. This route should lead to an individual person. We can do this by doing the following:

app.get("/people/:person",(req, resp)=> {
 resp.send(`Hello ${req.param.person}`)
 })

We have now learned how define our routes for some of our get requests, but we have not learned how to create our 404 or 500 errors.

To create a page to handle 404 errors is quite simple. We can do the following

app.use ((req,res,next) =>{
    res.status(404).send(`Your lost`)
})

If we try to visit a route not defined we will see Your lost display in browser now.

Let’s handle our 500 error differently and actually render an html file. To start lets create a folder called public outside of our src folder. In the public folder lets create a file called 500.html. and add the following:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        something is wrong
    </body>
</html>

With this now created, lets go back to the index.js and reference this. Before we do we need to reference path which is a library in Express. We can do this by adding:

let path = require(`path`)

Now we can reference the path in our get request. The get request for the 500 error should look like the following:

app.use((err,req,res,next)=>{
    console.error(err.stack)
    res.sendFile(path.join(__dirname, `../public/500.html`))
})

We have now accomplished created all of our error handling pages and have learned how to create get request to render certain pages. Next week we will learn how to create an API with MongoDB.

#node-js #express

Getting Started With Express
1 Likes34.65 GEEK