Skip to content
Cover image for "Creating a Basic Server Using NodeJS and ExpressJS" - Blog post by Muhammad Rivki about Javascript

Creating a Basic Server Using NodeJS and ExpressJS

Written on 3 min read
Available in:
🇺🇸EN🇮🇩ID

Previously, we learned how to create a web server using only NodeJS. This time, we'll try how to create a web server using ExpressJS, one of the most widely-used frameworks in NodeJS.

Why ExpressJS? In my opinion, ExpressJS is fast, minimalist, simple, and fairly easy to learn. Also, many other frameworks are built on ExpressJS; in other words, ExpressJS is the foundation.

Creating a Project

What you need to follow this tutorial is node and npm. If you haven't installed it locally yet, you can read this tutorial.

We'll start by creating a folder for our application, then accessing it via terminal:

$ mkdir express-app
$ cd express-app

To create a node app, we'll use the following command:

$ npm init

After that, some questions will appear for the package.json information. Just keep pressing enter for the default config.

Setting up Express

Now we'll install Express. Go to the terminal and enter the following command:

$ npm install express

Once it's done, create an index.js file in the root folder or at the same level as the package.json file. Then add the following syntax to the index.js file:

index.js
const express = require('express')
const app = express()
const PORT = 3000

app.get('/', (request, response) => {
  response.end('Hello ExpressJS')
})

app.listen(PORT, () => {
  console.log(`App running on http://localhost:${PORT}`)
})

First, we define Express using require and create an Express app by calling express().

Then we create a variable PORT with value 3000. By defining a variable, we make it clear what the number 3000 is for. Below that, we call app.get() to set our default route. The first parameter is the path / and the second parameter is a callback function with request and response parameters. It's not very different from using just NodeJS alone. Inside the function, we call response.end to send the response body to the client.

Below that, we call app.listen() with the PORT variable and a simple function to log in the terminal, so we know if our application is actually running.

Once done, try running our application using the command below in the terminal, making sure you're in the correct folder:

$ node index.js
Result
Running result

If you do it correctly, you'll see the result like the image above.

Summary || TLDR;

Building a web app using the ExpressJS framework will be easier and faster. But we still need to strengthen the basics first.

Why ExpressJS? In my opinion, ExpressJS is fast, minimalist, simple, and fairly easy to learn. Also, many other frameworks are based on ExpressJS; in other words, ExpressJS is the foundation.

Credits

Blog