- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Basic App
Creating a basic Express.js application is the first step toward mastering backend development with JavaScript. Express is the industry-standard "unopinionated" framework for Node.js, meaning it provides a robust set of features for web and mobile applications without forcing a specific project structure on you. Below is a step-by-step guide to building a functional web server that handles HTTP requests and returns responses.
Key Features of a Basic Express App
- Handles HTTP requests: Express makes routing straightforward. It listens for specific methods (GET, POST, PUT, DELETE) at specific URLs and executes code in response.
- Minimal setup: Unlike some "heavy" frameworks, Express stays out of your way. You only need a few lines of code to have a production-ready server running.
- Middleware support: This is the "secret sauce" of Express. Middleware functions allow you to execute code, change the request/response objects, or end the request-response cycle entirely.
Steps to Create a Basic Express App
Set up a New Node.js Project
Before writing any code, you need a package.json file to manage your project's metadata and dependencies. Initialize it by running the following command in your terminal:
npm init -y
-y flag tells npm to skip the setup questionnaire and use default values. You can always edit the package.json file later to add a description or change the version.
Install Express
Now, add Express to your project. This downloads the framework into a node_modules folder and updates your dependency list:
npm install express --save
npm not being found, make sure Node.js is installed on your system.
Create the Application File
Create a file called app.js in your project directory. This will be the entry point for your server. Copy and paste the following code, then read the explanations below:
const express = require('express');
const app = express();
// Define a route for the home page
app.get('/', (req, res) => {
res.send('Welcome to Express!');
});
// Define a route for another page
app.get('/about', (req, res) => {
res.send('This is the About page');
});
// Set the application to listen on port 3000
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Code Breakdown:
const app = express();: This creates an instance of an Express application.req(Request): Contains information about the incoming web request (headers, query parameters, etc.).res(Response): Used to send data back to the client.res.send()automatically sets the correct Content-Type header for you.
res.send(), res.json(), or res.end(). If you don't respond, the browser will keep spinning until the request times out.
Run the Application
To start your server, execute the following command in your terminal:
node app.js
You should see the message Server is running on port 3000. This means your computer is now acting as a local web server!
Test the Routes
Open your web browser and navigate to the following addresses to see your app in action:
http://localhost:3000/: You will see "Welcome to Express!"http://localhost:3000/about: You will see "This is the About page"
npm install -g nodemon and run your app with nodemon app.js. It will auto-restart whenever you save a file.
Optional: Add Middleware for Logging
In real-world apps, you need to know who is accessing your site. Middleware acts as a "bridge" that runs before your route handler. Add this block above your route definitions:
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware or route
});
next(), the request will hang and the route handlers below it will never execute.
Summary
Building a basic Express.js app is a straightforward process: initialize your project, install the package, define your routes, and start the listener. This minimal structure is incredibly powerful; it can be expanded into a REST API that serves JSON to a mobile app, or a full website that renders dynamic HTML. As you grow, you'll explore more advanced features like template engines, database integration, and security headers, but the core fundamentals remain the same.