Express JS: Essential Code Snippets
Express.js Cheat Sheet
Getting Started
- Install Express.js:
npm install express
- Import Express:
const express = require('express');
- Create an Express application:
const app = express();
Routing
- Define a route:
app.get('/route', (req, res) => { // Handle request });
- Route with parameters:
app.get('/users/:id', (req, res) => { const userId = req.params.id; // Handle user ID });
- Route with query parameters:
app.get('/search', (req, res) => { const query = req.query.q; // Handle search query });
Middleware
- Use middleware:
app.use(express.json()); // JSON body parser app.use(express.static('public')); // Static files
- Custom middleware:
const customMiddleware = (req, res, next) => { // Do something before route handler next(); // Call next middleware or route handler }; app.use(customMiddleware);
HTTP Methods
- GET:
app.get()
- POST:
app.post()
- PUT:
app.put()
- DELETE:
app.delete()
- PATCH:
app.patch()
Request and Response
req.params
: Route parametersreq.query
: Query parametersreq.body
: Request body (for JSON)req.headers
: Request headersres.send()
: Send response datares.json()
: Send JSON responseres.status()
: Set response status
Route Middleware
- Route-specific middleware:
const routeMiddleware = (req, res, next) => { // Middleware logic next(); }; app.get('/route', routeMiddleware, (req, res) => { // Route handler });
- Error handling middleware:
const errorHandler = (err, req, res, next) => { console.error(err); res.status(500).send('Something went wrong'); }; app.use(errorHandler);
Serving Views
- Set view engine:
app.set('view engine', 'ejs');
- Render views:
app.get('/view', (req, res) => { res.render('view', { data: 'Data to pass' }); });
Static Files
- Serve static files from a directory:
app.use(express.static('public'));
- Access files in HTML:
<link rel="stylesheet" href="/styles.css">
Redirects
- Redirect to a URL:
app.get('/old-url', (req, res) => { res.redirect('/new-url'); });
Error Handling
- Handle 404 Not Found:
app.use((req, res, next) => { res.status(404).send('Page not found'); });
- Handle errors:
app.use((err, req, res, next) => { console.error(err); res.status(500).send('Something went wrong'); });
Listen
- Start server:
const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
This cheat sheet covers essential concepts in Express.js. Remember to refer to the official Express.js documentation for detailed information and advanced usage.