Express.js : Introduction & Installation

What is Express.js?

Express.js is a web application framework for Node.js that simplifies building web applications and APIs. It provides tools for handling HTTP requests, routing, middleware, and more.

1. Installing Express.js

To start using Express.js, you need to install it in your Node.js project.

				
					npm init -y  # Initialize a Node project
npm install express  # Install Express.js

				
			
Basic Setup for running express
				
					const express = require('express');
const app = express(); // Creates an Express application

// Set the server to listen on a port
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

				
			
2. Creating Routes

Express allows you to create different routes (URLs) that your server responds to. You define routes based on HTTP methods such as GET, POST, PUT, DELETE. 

				
					//Example of GET Route
app.get('/', (req, res) => {
  res.send('Welcome to Express.js!');
});

app.get('/about', (req, res) => {
  res.send('About page');
});

				
			
  • 'app.get()' is used to define a route for GET requests.
  • 'req' is the request object, and res is the response object.
				
					// Example of Post Route
app.post('/submit', (req, res) => {
  res.send('Data received!');
});

				
			
3. Middleware

Middleware functions are functions that execute during the request-response cycle. You can use middleware to process data, check authentication, etc.

				
					// Simple middleware to log the request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Passes control to the next middleware or route
});

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

				
			

Built-in Middleware

  • express.json(): Parses incoming JSON requests.
  • express.urlencoded(): Parses URL-encoded form data.
				
					app.use(express.json()); // Middleware to handle JSON data
app.use(express.urlencoded({ extended: true })); // For form data

				
			
4. Routing Parameters

You can define dynamic routes using route parameters.

				
					// Example of Route Parameters
app.get('/user/:id', (req, res) => {
  const userId = req.params.id; // Accessing route parameters
  res.send(`User ID is: ${userId}`);
});

				
			
				
					//Query Parameters
app.get('/search', (req, res) => {
  const query = req.query.q; // Accessing query string parameters
  res.send(`Search query: ${query}`);
});

				
			
5. Serving Static Files

You can use Express to serve static files like HTML, CSS, and images.

				
					app.use(express.static('public')); // Folder for static files

// Now you can access files like public/style.css in the browser

				
			
6. Handling Forms and JSON Data

Ensure you use the express.json() middleware to parse the JSON request.

				
					//Example: Handling JSON Data (POST Request)
app.post('/data', (req, res) => {
  const data = req.body; // Data sent in the request body
  res.send(`Received data: ${JSON.stringify(data)}`);
});

				
			
7. HTTP Status Codes

You can send different HTTP status codes in responses, e.g., 200 for success, 404 for not found.

				
					//Example: Sending Status Codes
app.get('/notfound', (req, res) => {
  res.status(404).send('Page not found');
});

				
			
8. Express Router

For larger applications, you can split routes into separate modules using the express.Router().

				
					//Example of Using Express Router
const express = require('express');
const router = express.Router();

// Defining routes
router.get('/', (req, res) => {
  res.send('Home page');
});

router.get('/about', (req, res) => {
  res.send('About page');
});

// Export the router
module.exports = router;

// In the main app
const app = express();
const routes = require('./routes'); // Import routes

app.use('/', routes); // Use the routes

				
			
9. Error Handling

Express provides a way to handle errors in middleware.

You must include 4 arguments in the error-handling middleware (errreqresnext).

				
					//Example of Error Handling Middleware
app.use((err, req, res, next) => {
  console.error(err.stack); // Log the error
  res.status(500).send('Something went wrong!'); // Send error response
});

				
			
10. Handling 404 Errors

To handle 404 Not Found errors when no route matches the request.

				
					app.use((req, res) => {
  res.status(404).send('Page not found');
});

				
			
11. Connecting to a Database

Though Express.js doesn’t have a built-in database system, it works well with MongoDB, MySQL, etc. Here’s an example using MongoDB with Mongoose.

				
					//Example of Connecting to MongoDB
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydb', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Could not connect to MongoDB...', err));

// Now you can create models and perform database operations

				
			
12. Deployment

When deploying an Express app, the environment might provide the port number.

				
					const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

				
			

Important Points :

  • Express Setup : Install and start an Express app.
  • Routing : Handling different routes with GET, POST, etc.
  • Middleware : Functions that process requests before they reach the final route handler.
  • Parameters : Accessing route and query parameters.
  • Serving Static Files : Serve HTML, CSS, etc.
  • Form and JSON Handling : Process form data and JSON payloads.
  • Error Handling : Handle 404 and other errors gracefully.
  • Express Router : Modularize routes for larger applications.