Introduction to Express.js
Congratulations! You've built servers, handled routes, served files, and even created a REST API – all with pure Node.js. But you might have noticed that it takes a lot of code to do even simple things. That's where **Express.js** comes in.
What is Express.js?
Express.js is a minimal and flexible web application framework for Node.js. It provides a robust set of features for web and mobile applications, making it much easier to build servers and APIs.
If Node.js is the engine, Express is the comfortable car with power steering, automatic transmission, and GPS. It makes the journey much smoother.
Why Use Express?
- Simpler routing: `app.get()`, `app.post()` instead of manual if/else.
- Middleware: Powerful system to process requests.
- Body parsing: Built-in or easily added.
- Static file serving: One line to serve entire folders.
- Template engines: Support for EJS, Pug, etc.
- Huge ecosystem: Thousands of middleware packages.
Installing Express
First, create a new project and install Express:
mkdir my-express-appcd my-express-appnpm init -ynpm install expressYour First Express Server
Create `app.js`:
const express = require('express');const app = express();
<!-- Define a route -->app.get('/', (req, res) => { res.send('Hello from Express!');});
<!-- Start server -->app.listen(3000, () => { console.log('Express server running on port 3000');});Run it:
node app.jsExpress vs Pure Node.js
| Task | Pure Node.js | Express |
|---|---|---|
| Handle GET / | `if (req.url === '/') ...` | `app.get('/', handler)` |
| Get URL parameter | Parse manually with regex | `req.params.id` |
| Parse JSON body | Listen to data/end events | `express.json()` middleware |
| Serve static files | Manual file reading, MIME types | `express.static('public')` |
Basic Routing with Express
app.get('/about', (req, res) => { res.send('About page');});
app.post('/api/users', (req, res) => { <!-- Create user -->});Route Parameters
app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`);});Serving Static Files
app.use(express.static('public'));Two Minute Drill
- Express is a framework that simplifies Node.js web development.
- Install with `npm install express`.
- Create an app with `express()`.
- Define routes with `app.METHOD(path, handler)`.
- Access URL parameters via `req.params`.
- Serve static files with `express.static()`.
- Express is the foundation for thousands of web applications.
Need more clarification?
Drop us an email at career@quipoinfotech.com
