Getting Started With Express

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.

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

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Ecommerce MERN(MongoDB Express.js React.js Node.js) Redux Tailwind

Ecommerce MERN(MongoDB Express.js React.js Node.js) Redux Tailwind

Node.js Express MongoDB Tutorial

Node.js Express MongoDB Tutorial is CRUD example, I have created to showcase Express web framework, MongoDB NoSQL database, and Node.js server platform.

Node.js Express Tutorial | What Is Node.js Express

Express is a flexible Node.js web application framework which provides a wide set of features to develop both web and mobile applications. We dive into the features of this framework and also create a basic web application using Express.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.