- Express.js is a web application framework for Node.js that makes it easy to build web applications.
- To use Express.js, install it using npm by running
npm install express.
- Express.js provides features for handling HTTP requests, routes, middleware, templates, and more.
- To create an Express.js application, import the
expressmodule and create an instance of it:const express = require('express'); const app = express();
- You can define routes using
app.get(),app.post(),app.put(),app.delete(), and other methods.
- Middleware functions can be used to handle requests, modify the response, or perform other tasks. Use
app.use()to add middleware.
- You can serve static files using
express.static()and templates using a template engine like EJS or Pug.
- To start the Express.js application, use
app.listen(port, callback)whereportis the port number to listen on andcallbackis a function that runs when the server starts.
Â
- Routing: Express.js allows you to define routes to handle specific HTTP requests (GET, POST, PUT, DELETE, etc.) for different URL paths. For example:
app.get('/users', (req, res) => { res.send('List of users'); }); app.post('/users', (req, res) => { res.send('Create a new user'); });
- Middleware: Middleware functions are used to modify or process incoming requests before they reach the route handlers. You can create custom middleware or use built-in middleware like
express.json(),express.urlencoded(), andexpress.static().
app.use(express.json()); // Parse JSON request bodies app.use((req, res, next) => { console.log(`Request received: ${req.method} ${req.url}`); next(); // Continue to the next middleware or route handler });
- Request and Response objects: In route handlers, you have access to the
req(request) andres(response) objects. Use these to retrieve information about the request (e.g., headers, query parameters, and body) and send a response.
app.get('/greet/:name', (req, res) => { const name = req.params.name; res.send(`Hello, ${name}!`); });
- Error handling: Express.js allows you to define error-handling middleware to centralize error processing. Error-handling middleware functions have four arguments:
(err, req, res, next).
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong'); });
- Template engines: Express.js supports various template engines like EJS, Pug, and Handlebars to render dynamic HTML pages.
// Set up EJS as the template engine app.set('view engine', 'ejs'); // Render a template with data app.get('/profile', (req, res) => { res.render('profile', { name: 'John', age: 30 }); });
- Modularization: You can organize your code into separate modules using the
express.Router()class. This helps you maintain a clean and organized codebase.
// users.js const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { /* ... */ }); router.post('/', (req, res) => { /* ... */ }); module.exports = router; // app.js const users = require('./users'); app.use('/users', users);
To learn more and find examples, visit the Express.js documentation: https://expressjs.com/en/starter/basic-routing.html and https://expressjs.com/en/guide/routing.html.
Â

