Backend With Express.js Framework

Building a Backend with Express.js — Part 1 — #ExpressSeries — Episode #00

J3
Jungletronics
8 min read2 days ago

--

Greetings!!!

If you’re building a backend using JavaScript, then chances are you’re going to be using Express.js. In this tutorial, we’ll go through everything you need to know about Express, including a few features that you might not have seen in other tutorials. By the end of this tutorial, you will be an Express.js master.

Express is a lightweight Node.js framework for web and mobile apps. 
It simplifies API creation with many HTTP methods and middleware.
It enhances performance by adding minimal features to Node.js.
Express uses middleware modules to extend its flexible routing framework.

Let’s dive into the basics of Express.js together, so you can smoothly start using this fantastic web tool widely embraced by the community.

Welcome aboard! Official Documentations link.

Let’s Get Started!

Summary

Project Setup

Server Setup

Basic Routing

Sending Data

Rendering HTML

Advanced Routing

Chaining routes

👉GitHub

My System:

OS: Ubuntu 24.04 LTS
Processor: Intel® Core™ i7–9750H × 12 — 8.0 GiB RAM

Project Setup:

0#step —Install Node.js

Make sure you have Node.js installed on your system. If not, please install it from the official Node.js website.

Ubuntu terminal:

sudo apt install npm
npm install express

Then start your vscode:

cd ~/Documents
mkdir nodejs_projects
cd nodejs_projects
code .

1#step — Initialize a New Node.js Project

Open your vscode terminal and navigate to your project directory. Run the following command to create a package.json file:

npm init -y
npm i express

This will set up a basic package.json file and install the Express library.

2 #step — Install Nodemon

npm i --save-dev nodemon

Nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected. Install it as a development dependency.

3 #step — Setup package.json Scripts

Open your package.json file and modify the following scripts:

main: "server.js"

"scripts": {
"devStart": "nodemon server.js"
},

4 #step — Create the Server File

Create a file named server.js in your project root directory. This is where you'll write all your server code and test nodemon.

On terminal type:

npm run devStart

Open server.js, make the necessary changes…

console.log('Hi nodejs!')

…and save the file.

Once we save it, the server file automatically re-runs:

npm run devStart

> nodejs_projects@1.0.0 devStart
> nodemon server.js

[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js`
Hi nodejs!
[nodemon] clean exit - waiting for changes before restart

Everything is running smoothly so far, thanks to nodemon.

Server Setup:

5#step — Require Express and Set up the Server to Listen on a Port

In your server.js file, require Express and create an app instance:

const express = require('express')
const app = express()
const PORT = 3000
// Routing configuration goes here.
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})

Open your browser and go to http://localhost:3000. You should see a message saying Cannot GET / which means your server is running but doesn't have any routes set up yet.

Error : 🤔 All this means is that our application doesn’t have any routes set up. When we try to access the index route (just a slash ‘/’), it’s saying it can’t find this route.

Basic Routing:

6#step — Set up a Basic Route

Add a route to handle GET requests to the root URL:

app.get('/', (req, res) => {
res.send('Hello World')
})

Test the Route: Save your changes and refresh the browser. You should see Hello World.

The URL ‘/’ will send the information directly to that user. ☺️

Sending Data:

7#step — Sending JSON Data

Instead of sending plain text, you might want to send JSON data. Modify your route to send JSON:

app.get('/', (req, res) => {
res.json({ message: 'Hello World' })
});
The message is now more verbose (25 chars), but sending JSON to clients is advantageous because it is lightweight, easy to parse, and widely supported across various programming languages, ensuring efficient and seamless data exchange.

Sending Status Codes: You can also send status codes along with your responses:

app.get('/error', (req, res) => {
res.status(500).json({ message: 'Internal Server Error' })
})

Alternatively, send an entire file for download:

app.get('/', (req, res) => {
res.download('server.js')
})

Let’s render an HTML file. By default, files will be served from a folder called views.

8#step — Create a views Directory

Create a views directory in your project root. Inside this directory, place your index.html file.

views/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express App</title>
</head>
<body>
<h1>Hello Express!</h1>
</body>
</html>

But when rendering this file…

app.get('/', (req, res) => {
console.log("Rendering index.html...")
res.render('index')
});

And this error is thrown:

Error: No default engine was specified and no extension was provided.
....

We don’t have a view engine set up yet. Using a view engine allows your server to generate dynamic content for your views. For instance, you can pass information from your server to your views. There are several view engines available, but we will use EJS because it’s similar to HTML. EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.

To set up our application, we need to specify where our view files are located and tell the system what view engine to use.

By default, as said, these files will be in a folder called views.

Rendering HTML

9 #step — Set up a View Engine:

Install EJS as your view engine:

ctrl + c
npm install ejs

Set it up in your server.js:

app.set('view engine', 'ejs');

Change the file extension: Rename the index.html file in the views directory to index.ejs.

Restart the server: on Terminal type:

npm run devStart

Then browse again.

Now everything in HTML can be rendered using EJS. Awesome! 🥰

Render the EJS file and Pass the Information: You can pass information from your server to your views by using the render function, which takes a second parameter. This parameter is an object where you can include any data you want to pass.

Modify your route to set the message variable .

server.js

app.get('/', (req, res) => {
res.render('index', { message: 'Hello Express!' })
})

Now access the message variable passed from your route.

views/index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express App</title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>

For syntax highlighting in EJS, make sure to install the EJS Language Support extension in VS Code.

EJS language support for Visual Studio Code. Place a percent sign followed by an equal sign <#= enclosed code %>. This indicates that the server should run the enclosed code and output the result to the page.

If our application has hundreds of different routes, the main file server.js would become huge and difficult to manage. To solve this, Express introduced the concept of a router. A router allows you to create separate instances of your application, each with its own logic, which can then be easily integrated into the main app.

Advanced Routing

10 #step — Create a Router: Organize your routes using Express Router. Create a directory named routes and inside it, create a file named users.js.

routes/users.js

const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {
res.send('User List')
})

router.get('/new', (req, res) => {
res.send('User New Form')
});

module.exports = router

A router acts like a mini-app within our main application. It operates independently but is part of the larger app, meaning the settings in this router are separate from those in the main router.

11#step — Use the Router in Your Server: In your server.js, import and use the router:

server.js

const userRouter = require('./routes/users');
app.use('/users', userRouter)

Routes starting with / or /new can include sub-routes , like /users and /users/new. This helps organize routes without repeating names. See step#9.

http://localhost:3000/users
http://localhost:3000/users/new

Dynamic Routes: To handle different user IDs, use this:

routes/users.js

router.get('/:id', (req, res) => {
res.send(`User with ID ${req.params.id}`);
})

Handling POST Requests: To add a route for handling POST requests, use this:

routes/users.js

router.post('/', (req, res) => {
res.send('Create User');
})

Chaining Routes

12#step — Using router.route to Clean Up Code

You can chain route methods using router.route:

routes/users.js

const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {
res.send('User List')
})

router.get('/new', (req, res) => {
res.send('User New Form')
});

// router.get('/:id', (req, res) => {
// res.send(`User with ID ${req.params.id}`);
// });

router.route('/:id')
.post((req, res) => {
const userId = req.params.id;
res.send(`Post the user with ID ${userId}`)
})
.get((req, res) => {
const userId = req.params.id;
res.send(`Get the user with ID ${userId}`)
})
.put((req, res) => {
const userId = req.params.id;
res.send(`Update user with ID ${userId}`)
})
.delete((req, res) => {
const userId = req.params.id;
res.send(`Delete user with ID ${userId}`)
})

module.exports = router

To test: Example Request Using curl:

If you wanted to test all the CRUD operations, you could use the following curl commands:

curl -X GET http://localhost:3000/users/1
curl -X POST http://localhost:3000/users/1
curl -X PUT http://localhost:3000/users/1
curl -X DELETE http://localhost:3000/users/1

To test: as alternative you can use Advanced Rest Client if your browse is Chrome or as I am using Rested in Firefox:

GET: localhost:3000/users/1
POST: localhost:3000/users/1
DELETE: localhost:3000/users/1
PUT: localhost:3000/users/1

Conclusion

These steps set up a basic Express.js application that handles routing, sends data, renders HTML, and organizes routes using routers. You can extend this further by adding more features, middleware, and advanced routing techniques as needed. These enhancements will be covered in the next episode.

See you soon!

Bye!

👉GitHub v1

https://gouravmukhija.medium.com/what-is-expressjs-64b0b4334f2e

Related Posts:

00#Episode — Backend With Express.js Framework — Building a Backend with Express.js — Part 1 (this one)

01#Episode — Backend With Express.js Middleware — Building a Backend with Express.js — Part 2

Acknowledgements:

TAG IT ALL!

🤔☺️👉🥰
git tag -a express_v1 -m "Express in Nodejs 1 - v1.0: Go to https://medium.com/jungletronics/backend-with-express-js-framework-3ea4b49f2610" -m "0- Project Setup;" -m "1- Basic Routing;" -m "2- Sending Data;" -m "3- Rendering HTML" -m "4- Advanced Routing" -m "5- Chaining routes" -m "Thank you for downloading this project 😘️👌️👋️😍️"
git push origin express_v1

Release V1

GitHub: https://github.com/giljr/express_project

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!