Express.js
Shared by a Flashcards.gg user · generated with AI · Report this set
This set covers core Express.js framework concepts and methods for backend developers.
Tap the card to flip it
Cards · 20
- Initialize an Express application
- const express = require('express'); const app = express();
- Start the server on a specific port
- app.listen(3000, () => console.log('Server running on port 3000'));
- Define a basic GET route
- app.get('/users', (req, res) => res.send('Get all users'));
- Define a basic POST route
- app.post('/users', (req, res) => res.status(201).send('User created'));
- Enable built-in JSON body parsing middleware
- app.use(express.json());
- Enable URL-encoded form data parsing middleware
- app.use(express.urlencoded({ extended: true }));
- Access route path parameters
- app.get('/users/:id', (req, res) => res.send(req.params.id));
- Access query string parameters
- app.get('/search', (req, res) => res.send(req.query.q));
- Send a JSON response
- app.get('/api/data', (req, res) => res.json({ status: 'ok' }));
- Set HTTP status code explicitly
- app.get('/not-found', (req, res) => res.status(404).send('Resource not found'));
- Serve static files from a directory
- app.use('/static', express.static('public'));
- Create and use custom middleware
- app.use((req, res, next) => { console.log(req.method, req.url); next(); });
- Define a global error handling middleware
- app.use((err, req, res, next) => res.status(500).send(err.message));
- Create a modular route handler using Router
- const router = express.Router(); router.get('/', (req, res) => res.send('Home'));
- Mount a modular router onto an app path
- const usersRouter = require('./users'); app.use('/users', usersRouter);
- Send a file as a response
- app.get('/download', (req, res) => res.sendFile('/path/to/file.pdf'));
- Redirect a request to another URL
- app.get('/old-path', (req, res) => res.redirect(301, '/new-path'));
- Set custom HTTP response headers
- app.get('/custom', (req, res) => res.set('X-Custom-Header', 'Value').send('Done'));
- Handle PUT requests to update resources
- app.put('/users/:id', (req, res) => res.send(`Updated user ${req.params.id}`));
- Handle DELETE requests to remove resources
- app.delete('/users/:id', (req, res) => res.status(204).end());