Express.
js
Installation
npm install express
Basic Setup
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Middleware
Built-in Middleware
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
app.use(express.static('public')); // Serve static files
Custom Middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
Routing
Basic Routing
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.post('/submit', (req, res) => {
res.send('Data received');
});
Route Parameters
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Query Parameters
app.get('/search', (req, res) => {
res.send(`Search Query: ${req.query.q}`);
});
Handling Requests and Responses
Request Object
app.get('/', (req, res) => {
console.log(req.query); // Query params
console.log(req.params); // Route params
console.log(req.body); // Body data (requires middleware)
res.send('Request received');
});
Response Object
app.get('/', (req, res) => {
res.status(200).send('Success'); // Status and body
res.json({ message: 'Hello, World!' }); // JSON response
res.redirect('/another-route'); // Redirect
});
Route Grouping
const router = express.Router();
router.get('/users', (req, res) => {
res.send('Get all users');
});
router.post('/users', (req, res) => {
res.send('Create a user');
});
app.use('/api', router);
Error Handling
Basic Error Handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
404 Handling
app.use((req, res) => {
res.status(404).send('Sorry, we could not find that!');
});
Working with Templates
Setting Up EJS
npm install ejs
app.set('view engine', 'ejs');
app.get('/home', (req, res) => {
res.render('index', { title: 'Home Page' });
});
Example EJS Template (views/index.ejs)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome to the <%= title %></h1>
</body>
</html>
Serving Static Files
app.use('/static', express.static('public'));
// Now you can access files in the 'public' folder via /static route
Using Third-party Middleware
Example: Cookie Parser
npm install cookie-parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/', (req, res) => {
res.cookie('name', 'express').send('Cookie set');
});
CORS with Express.js
Installing CORS
npm install cors
Basic Setup
To enable CORS for all routes:
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.get('/', (req, res) => {
res.send('CORS enabled for all origins');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Enabling CORS for Specific Routes
You can enable CORS for specific routes by passing the cors middleware as an argument to the
route.
app.get('/public', cors(), (req, res) => {
res.send('CORS enabled for this route');
});
Configuring CORS
You can customize the behavior of CORS by passing an options object.
const corsOptions = {
origin: 'http://example.com', // Allow only this origin
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Allowed methods
allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers
credentials: true, // Allow cookies to be sent
optionsSuccessStatus: 204 // Some legacy browsers choke on 204
};
app.use(cors(corsOptions));