The Web Developer Bootcamp 2024

Colt Steele

Back to Express Index Page


 

Express Js
Installing Express

There is a very good explanation of how to get express up and running on their website, found here, so we're going to just follow along. The first thing we need to do when creating our first express app is to create our "Parent" directory.

  • mkdir myapp
  • cd myapp

Use the [npm init] command to create the package.json file for your application. We are using the default index.js as our file name.

  • npm init

Next, install Express in the [myapp] directory and save it in the dependencies list. For example:

  • npm (i)nstall express
This creates our node_modules folder with all the packages that express requires. It also updates the dependencies in our package.json file to reflect our version of express, which should now be installed into our working directory.


Hello World

We can now create or first express app. We are going to create the standard "Hello World" app. This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

  • JavaScript
  • index.js
  • const express = require('express');
  • const app = express();
  • const port = 3000
  • // response for requests to the root URL (/)
  • app.get('/', (req, res) => {
    • res.send('Hello World!')
  • })
  • // starts the server : listens for response
  • app.listen(port, () => {
    • console.log(`App Server is running : Listening on port ${port}`)
  • })

A note about ports. This little app is set up to run on port 3000. In most cases, when running a localhost server, we usually set it up to run on either port 8080, or port 3000.


Running the App

We can now run the app with the following command:

  • node index.js
Then, load http://localhost:3000/ into a browser to see the output.

When you're finished, you press ctrl/c in the Terminal to stop the server.


Back to Top