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!");
And test it out
$ node server.js
Hello world!
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
Step 3: Install and import express middleware
A middleware is a piece of code that has access to the
request
andresponse
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
// server.js
const express = require('express');
const server = express();
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" });
});
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');
});
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>
Step 5: Start server
// server.js
...
const port = 4000;
server.listen(port, () => {
console.log(`Server listening at ${port}`);
});
# CTRL+C to stop server if currently running
$ npm start
Step 6: Test
# on another terminal
$ curl http://localhost:4000/json
{"message":"Hello world"}
$ curl http://localhost:4000
<!-- index.html --> ...
Or open a browser and go to
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}`);
});
"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');
});
...
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:
Article No Longer Available
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):
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!
Top comments (2)
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.....!
This is a pretty quick tutorial, helpful. Thanks