Setting up an Express.js application involves several steps, from installing the necessary tools to creating a basic server, adding routes, and implementing advanced features. This chapter will guide you through the entire process, ensuring you have a solid foundation for building Express.js applications.
Before you start setting up an Express.js application, make sure you have the following:
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. NPM (Node Package Manager) is included with Node.js and is used to install packages.
To verify the installation, open your terminal or command prompt and run:
node -v
npm -v
This should display the installed versions of Node.js and NPM.
To start a new Node.js project, you need to create a project directory and initialize it.
Create a new directory for your project.
mkdir my-express-app
cd my-express-app
Initialize a new Node.js project.
npm init -y
This will create a package.json
file with default settings.
Express.js can be installed using NPM. This package will provide the core functionality for your application.
npm install express
This will add Express.js to your project and update the package.json
file with the dependency.
With Express.js installed, you can create a basic server to handle HTTP requests and responses.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
require('express')
: Imports the Express.js module.const app = express()
: Creates an Express application.app.get('/', (req, res) => {...})
: Defines a route for the root URL that sends a “Hello, World!” response.app.listen(PORT, () => {...})
: Starts the server on the specified port.Output: When you navigate to http://localhost:3000
in your browser, you will see “Hello, World!”.
Routes are used to define the endpoints of your application. Each route can handle different types of HTTP requests.
app.get('/about', (req, res) => {
res.send('About Page');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
app.get('/about', (req, res) => {...})
: Defines a GET route for the /about
URL.app.post('/submit', (req, res) => {...})
: Defines a POST route for the /submit
URL.http://localhost:3000/about
displays “About Page”.http://localhost:3000/submit
displays “Form Submitted”.Middleware functions are used to handle various tasks such as logging, parsing request bodies, and authentication.
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next();
});
app.use(express.json());
app.use((req, res, next) => {...})
: Logs each request’s method and URL.app.use(express.json())
: Parses incoming JSON request bodies.Output: Each request will be logged in the console, and JSON request bodies will be automatically parsed.
Express can serve static files such as HTML, CSS, and JavaScript.
app.use(express.static('public'));
app.use(express.static('public'))
: Serves static files from the public
directory.Output: Files in the public
directory will be accessible via URLs like http://localhost:3000/file.html
.
Template engines allow you to generate HTML dynamically. Express supports various template engines such as Pug, EJS, and Handlebars.
npm install pug
app.set('view engine', 'pug');
app.set('views', './views');
app.get('/template', (req, res) => {
res.render('index', { title: 'Express', message: 'Hello, Pug!' });
});
views/index.pug
).
html
head
title= title
body
h1= message
Output: Navigating to http://localhost:3000/template
will render the Pug template with the title “Express” and the message “Hello, Pug!”.
Error handling middleware functions handle errors that occur in the application.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.use((err, req, res, next) => {...})
: Handles errors and sends a 500 status code with an error message.Output: If an error occurs, the console will log the error stack, and the response will be “Something went wrong!”.
Environment variables are used to configure the application without hardcoding values.
dotenv
.
npm install dotenv
.env
file.
PORT=3000
require('dotenv').config();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Output: The server will start on the port specified in the .env
file or default to 3000.
Express.js can be integrated with various databases. Here, we will use MongoDB with Mongoose.
npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model('User', userSchema);
app.post('/users', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email
});
await user.save();
res.status(201).send(user);
});
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
mongoose.connect(...)
: Connects to the MongoDB database.const userSchema = new mongoose.Schema(...)
: Defines a schema for the User model.const User = mongoose.model('User', userSchema)
: Creates a User model.app.post('/users', async (req, res) => {...})
: Adds a new user to the database.app.get('/users', async (req, res) => {...})
: Retrieves all users from the database.Output: Using tools like Postman, you can add and retrieve users from the MongoDB database.
my-express-app/
├── public/
│ └── index.html
├── views/
│ └── index.pug
├── .env
├── app.js
├── package.json
└── package-lock.json
PORT=3000
MONGO_URI=mongodb://localhost:27017/test
Express App
Welcome to the Express App
This is a static file served by Express.
doctype html
html
head
title= title
body
h1= message
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));
// Define User schema and model
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model('User', userSchema);
// Middleware
app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next();
});
// Routes
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/template', (req, res) => {
res.render('index', { title: 'Express', message: 'Hello, Pug!' });
});
app.post('/users', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email
});
await user.save();
res.status(201).send(user);
});
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
// Set view engine
app.set('view engine', 'pug');
app.set('views', './views');
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
.env
file contains the port number and MongoDB URI. The dotenv
package loads these variables into the application.public/index.html
file is served statically by Express.views/index.pug
file is a Pug template rendered by Express./
, /about
, /template
, /users
).
npm install express mongoose pug dotenv
node app.js
http://localhost:3000
in your browser: You will see “Hello, World!”.http://localhost:3000/about
in your browser: You will see “About Page”.http://localhost:3000/template
in your browser: You will see the Pug template rendered with the message “Hello, Pug!”.http://localhost:3000/index.html
in your browser: You will see the static HTML file./users
endpoint:/users
: Retrieve the list of users./users
: Add a new user by sending a JSON payload with name
and email
fields.Setting up an Express.js application involves several steps, from installing the necessary tools to creating a basic server, adding routes, implementing middleware, and connecting to a database. By following this guide, you should have a comprehensive understanding of how to set up and configure an Express.js application. This foundation will enable you to build scalable and maintainable web applications with ease. Happy coding !❤️