Welcome to the Express.js tutorial! Express.js is a popular web application framework for Node.js that simplifies the process of building robust and scalable web applications. In this tutorial, we will cover the basics of Express.js along with numerous examples to help you get started.
Table of Contents
- Installation
- Basic Setup
- Routing
- Middleware
- Static Files
- Template Engines
- Error Handling
- API Endpoints
Let's dive right in!
1. Installation
First, make sure you have Node.js and npm (Node Package Manager) installed. You can download them from the official Node.js website.
To create a new Express.js application, open your terminal and run the following command:
npm install express --save
2. Basic Setup
Create a new file named app.js and add the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Run the application using:
node app.js
Visit http://localhost:3000 in your browser to see the "Hello, Express!" message.
3. Routing
Express allows you to define routes for different URLs. Add the following code to app.js:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
4. Middleware
Middleware functions are executed before the main request handler. They are used for tasks such as authentication, logging, etc. Create a simple middleware:
const logger = (req, res, next) => {
console.log(`Visited: ${req.url}`);
next();
};
app.use(logger);
5. Static Files
Serve static files like CSS, images, and JavaScript using the express.static middleware. Create a public folder in your project directory and place your static files there.
app.use(express.static('public'));
6. Template Engines
Express can render dynamic content using template engines like EJS or Pug. Install the EJS template engine:
npm install ejs --save
Configure Express to use EJS:
app.set('view engine', 'ejs');
Create an views folder and add an EJS file, e.g., home.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Express EJS</title>
</head>
<body>
<h1><%= title %></h1>
</body>
</html>
Render the EJS template:
app.get('/ejs-example', (req, res) => {
res.render('home', { title: 'EJS Example' });
});
7. Error Handling
Handle errors using middleware with four parameters (err, req, res, next). Add the following at the end of app.js:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
8. API Endpoints
Create API endpoints that return JSON data:
app.get('/api/users', (req, res) => {
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
res.json(users);
});
This concludes our Express.js tutorial with examples! Feel free to explore more features of Express and build amazing web applications.
Remember that this tutorial only scratches the surface of what Express.js can do. For more advanced topics, refer to the official Express.js documentation. Happy coding!
Top comments (0)