Express.js is a powerful and minimalist web application framework for Node.js. It simplifies the process of building web applications and APIs, making it a popular choice among developers. In this guide, we'll explore the core concepts of Express.js with practical examples to get you started.
Before we dive into Express.js, make sure you have Node.js installed on your system. You can download it from nodejs.org as like the previous lesson.
You can create a new Node.js project and install Express.js using the following steps:
mkdir my-express-app
cd my-express-app
npm init -y
npm install express --save
Let's create a basic Express application that responds with "Hello, Express!" when you access it in a web browser. Create a file named app.js
with the following code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
In this code:
To run the application, use the following command:
node app.js
Visit http://localhost:3000
in your web browser, and you should see "Hello, Express!" displayed.
Routing in Express allows you to define how your application responds to specific client requests. Let's create a simple route that displays "About Us" when you access /about
:
app.get('/about', (req, res) => {
res.send('About Us');
});
Now, when you visit http://localhost:3000/about
, you'll see "About Us" in your browser.
Express.js provides req
(request) and res
(response) objects to handle incoming requests and send responses. You can access request parameters, headers, and bodies, as well as send responses with various status codes.
For example, you can capture query parameters from a URL like this:
app.get('/greet', (req, res) => {
const name = req.query.name || 'Guest';
res.send(`Hello, ${name}!`);
});
Accessing http://localhost:3000/greet?name=John
will result in "Hello, John!" being displayed, while accessing http://localhost:3000/greet
will display "Hello, Guest!".
This is just the beginning of your journey with Express.js. You've learned the basics of setting up an Express application, routing, and working with request and response objects. Express.js is a versatile framework with a wide range of features and middleware to explore. It's ideal for building web applications, RESTful APIs, and more.
To continue your learning, explore topics like middleware, templating engines, handling forms, and integrating databases. The Express.js documentation is a valuable resource to dive deeper into this powerful framework.
Happy coding with Express.js!