Express.js, a web application framework designed for Node.js, streamlines the development of resilient and scalable web applications. It provides a set of features for building web and mobile applications and is designed to be minimal and flexible, allowing developers to create applications with a variety of functionalities.
Here’s a simple example to help you understand how to use Express.js:
Installation:
– To install Express.js, utilize npm (Node Package Manager). Open the terminal and write the below command:
npm install express
Creating an Express App:
Create a file with the name app.js and set a basic Express application.
// app.js
// Import required modules
const express = require('express');
// Create an Express application
const app = express();
// Define a route
app.get(‘/’, (req, res) => {
res.send(‘Hello, Express!’);
});
// Start the server on port 3000
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});/ Import required modules
In this example, we’ve created a simple Express app that listens for requests on the root path (‘/’) and responds with “Hello, Express!”.
Run the Application:
– Save your file (app.js) and run it using Node.js:
node app.js
Visit http://localhost:5000 in your web browser, and you should see the “Hello, Express!” message.
Handling Different Routes:
Extend your application to handle different routes.
// app.js
// … (previous code)
// Define additional routes
app.get(‘/about’, (req, res) => {
res.send(‘About Us’);
});
app.get(‘/contact’, (req, res) => {
res.send(‘Contact Us’);
});
Now, if you visit http://localhost:5000/about or http://localhost:5000/contact, you’ll see the corresponding messages.
Express.js provides middleware, routing, template engines, and other features to help you build more complex web applications. This is just a basic example, and as your application grows, you can leverage features like middleware for handling requests, template engines for rendering dynamic content, and routers for organizing your code.