DEV Community

Cover image for Your first Web Server with Node and Express in 5 minutes
Lenmor Ld
Lenmor Ld

Posted on • Updated on

Node Express Your first Web Server with Node and Express in 5 minutes

I know, I know... Another Node Express tutorial 😑.
But if you still haven't got around to learning Node and building a server, maybe this super-quick tutorial is the one you're waiting for! 😆

Step 1: Install node

Ok, this must take more than 5 minutes, but if you have Node already, skip this and let's go!

Install latest LTS version for your OS

https://nodejs.org/en/download/

To test if it works, create a file server.js in your project root

// server.js
console.log("Hello World!");
Enter fullscreen mode Exit fullscreen mode

And test it out

$ node server.js
Hello world!
Enter fullscreen mode Exit fullscreen mode

Nice! We're ready to do some backend-fu!

Step 2: Setup npm

We use NPM to manage our node packages.
Initialize npm and let it take defaults.

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 3: Install and import express middleware

A middleware is a piece of code that has access to the request and response object. For now, think about express making things easier for us by being a "middle-man" 🕵️ between our code and Node's HTTP stuff.

$ npm install express
Enter fullscreen mode Exit fullscreen mode
// server.js
const express = require('express');
const server = express();
Enter fullscreen mode Exit fullscreen mode

Step 4: Add a JSON route handler

Whenever client requests/accesses "/json" (localhost:4000/json), send JSON which is "Hello world" message

// server.js
...
server.get("/json", (req, res) => {
   res.json({ message: "Hello world" });
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Add a HTML route handler

Whenever client requests/accesses "/" (localhost:4000), send file which is an HTML page

__dirname holds the directory of current module (server.js)

// server.js
...
server.get("/", (req, res) => {
   res.sendFile(__dirname + '/index.html');
});
Enter fullscreen mode Exit fullscreen mode

Create index.html in same level as server.js
Go to town with the HTML! Or you can copy-paste this if you like blue headings.

<!DOCTYPE html>
<html lang="en">
 <head>
   <title>Node Workshop</title>
 </head>
 <body>
     <h1 style="color: blue;">
        Express: HELLO WORLD
     </h1>
 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Start server

// server.js
...
const port = 4000;

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
Enter fullscreen mode Exit fullscreen mode
# CTRL+C to stop server if currently running
$ npm start
Enter fullscreen mode Exit fullscreen mode

Step 6: Test

# on another terminal

$ curl http://localhost:4000/json
{"message":"Hello world"}

$ curl http://localhost:4000
<!-- index.html --> ...
Enter fullscreen mode Exit fullscreen mode

Or open a browser and go to

hackerman

hackerman

Complete Code

const express = require('express');
const server = express();
const port = 4000;

server.get("/", (req, res) => {
   res.sendFile(__dirname + '/index.html');
});

server.get("/json", (req, res) => {
   res.json({ message: "Hello world" });
});

server.listen(port, () => {
    console.log(`Server listening at ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

"Okay, that was nice. But what can I do with this? "

Add a few more routes and HTML pages
and you got yourself an HTML + JSON server!

...
server.get("/items", (req, res) => {
   res.json({ items: [{ "id": 1, "name": "banana" }, 
                      { "id": 2, "name": "apple" }
                     ] 
           });
});

server.get("/info", (req, res) => {
   res.sendFile(__dirname + '/info.html');
});
...
Enter fullscreen mode Exit fullscreen mode

We will need to cover more stuff to

  • build a REST(ful) API Server that implements GET / POST / PUT / DELETE
  • serve templates that accept data (instead of static HTML)
  • much more!

Next up:

This article is part of a Node+Express series I'm working on.

For the meantime, if you can't get enough of Node+Express 🤓,
checkout my Node workshop (Gihub repo and slides):

GitHub logo lenmorld / node_workshop

Build a server and API for your next web application, using Node, Express and MongoDB

Node workshop

Create a server + REST API for your next web application!

In this workshop, we’ll discuss concepts and put them to practice with activities, all about web servers The code and concepts here would be a great foundation for your next web project Topics include, but not limited to:

  • Using Node and Express to build a web server and REST API
  • Understanding routing, request and response
  • Implementing CRUD with HTTP methods
  • Building a server-rendered website using templates
  • Connecting to a Cloud NoSQL database: MongoDB Atlas DB
  • User authentication with sessions, cookies and tokens
  • Using external APIs, such as Github Jobs, Giphy, Spotify

Previous Events

Material

Preview slides: Google Drive document

Material: Notion link

Code

to follow workshop:

$ git checkout dev
$ node server.js

to dev latest

$ git checkout master
$
…






Here we discussed:
  • Using Node and Express
  • Routing, request and response
  • Building a REST API
  • Server-rendered templates
  • Connecting to a NoSQL (mongo) database
  • Using external APIs, such as Spotify
  • and much more!

Thanks for reading my first Dev post!
Happy server-ing!

Discussion (2)

Collapse
randall72096766 profile image
RandallArmstrong

Hello Everyone,

Thanks for sharing the amazing information with us.

Are you looking for a quick service with node js and express in 5 minutes only?

Now, there are many node.js hosting services available in the market. But choose the best one for our business website is a very important part. We help you to install the node server in just a few minutes.

DomainRacer is one of the best and quick web hosting for node js. They easily manage all types of servers in just a few seconds. Its features and affordable pricing let it stand out from the crowd. They believe in delivering service instead of aggressive marketing.

So, I strongly recommended DomainRacer. Because it gives a reasonable cost.

Best Luck.....!

Collapse
daxlooopy profile image
Abdulaziz Sadi

This is a pretty quick tutorial, helpful. Thanks