Introduction
Express is one of the most popular web application frameworks for Node.js. It provides a simple and flexible way to create web applications and APIs. Express is designed to work with Node.js to handle HTTP requests and responses. It is built on top of Node.js' core modules, such as http and fs, and provides additional functionality to create powerful web applications. In this article, we will cover the basics of Express, including how to set it up and create a simple web application.
Setting up Express
To set up Express, you will first need to have Node.js installed on your system. Once you have Node.js installed, you can create a new project directory and initialize it with npm. To do this, open your terminal and type the following commands:
mkdir my-express-app
cd my-express-app
npm init -y
This will create a new directory called "my-express-app", change into that directory, and initialize a new npm project with default values. Next, you will need to install Express as a dependency for your project. To do this, run the following command in your terminal:
npm install express
This will install the latest version of Express and save it as a dependency in your project's package.json file. With Express installed, you can now start building your web application.
Creating a simple web application
To create a simple web application with Express, you will need to create a new JavaScript file and require the Express module. Once you have done this, you can create a new Express application and define routes for handling HTTP requests. Here is an example of a simple Express web application:
// Require the Express module
const express = require('express')
// Create a new Express application
const app = express()
// Define a route for handling GET requests
app.get('/', (req, res) => {
res.send('Hello, World!')
})
// Start the server
app.listen(3000, () => {
console.log('Server listening on port 3000')
})
In this example, we first require the Express module and create a new Express application using the express() function. We then define a route for handling GET requests to the root URL ("/"). When a user makes a GET request to this URL, the server will respond with the message "Hello, World!". Finally, we start the server listening on port 3000.
Handling HTTP requests
Express provides a simple and flexible way to handle HTTP requests. You can define routes for handling requests with different HTTP methods (GET, POST, PUT, DELETE, etc.), as well as handle static files, middleware, and more.
Defining routes
To define a route in Express, you can use the app.METHOD() functions, where METHOD is the HTTP method for the route. For example, to define a route for handling GET requests to the URL "/users", you can use the app.get() function, like this:
app.get('/users', (req, res) => {
// handle GET request to /users
})
You can also define routes with parameters, which allow you to capture dynamic values in the URL. For example, to define a route for handling GET requests to the URL "/users/:id", where ":id" is a parameter representing the user ID, you can use the app.get() function with a parameter, like this:
Handling static files
Express also provides a way to serve static files, such as HTML, CSS, and JavaScript files. To do this, you can use the express.static() middleware function. This function takes a directory path as an argument and serves any files in that directory to the client. For example, if you have a directory called "public" with an index.html file, you can serve that file to the client using the following code:
app.use(express.static('public'))
This will serve any files in the "public" directory to the client. If the client requests a file that does not exist in the "public" directory, Express will return a 404 error.
Using middleware
Middleware functions are functions that can be called before or after a route handler to perform additional actions, such as logging, authentication, or data validation. Express provides a way to use middleware functions using the app.use() function. For example, to log all incoming requests to the server, you can create a middleware function that logs the request information and use it like this:
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`)
next()
}
app.use(logger)
This middleware function takes three arguments: req (the request object), res (the response object), and next (a function that calls the next middleware function). In this example, the middleware function logs the HTTP method and URL of the incoming request, then calls the next middleware function using the next() function.
Using templates
Express provides a way to render dynamic HTML templates using template engines. Template engines allow you to define HTML templates with placeholders for dynamic data, and then render those templates with data from your application. Express supports a variety of template engines, including EJS, Handlebars, and Pug.
To use a template engine in Express, you first need to install it as a dependency in your project. For example, to use the EJS template engine, you can run the following command in your terminal:
npm install ejs
Once you have installed the template engine, you can set it up in your Express application using the app.set() function. For example, to use the EJS template engine, you can use the following code:
app.set('view engine', 'ejs')
This sets the "view engine" setting to "ejs", telling Express to use the EJS template engine.
To render a template in Express, you can use the res.render() function. This function takes the name of the template file and an object containing the data to be rendered in the template. For example, to render a template called "index.ejs" with a title and message variable, you can use the following code:
app.get('/', (req, res) => {
const data = {
title: 'My Website',
message: 'Welcome to my website!'
}
res.render('index', data)
})
This will render the "index.ejs" template with the data object passed in, replacing any placeholders in the template with the corresponding data values.
Conclusion
In conclusion, Express is a powerful and flexible web application framework for Node.js. It provides a simple and intuitive way to handle HTTP requests, serve static files, use middleware, and render dynamic templates. With its robust ecosystem and active community, Express is a great choice for building web applications and APIs. By following the basics covered in this article, you can get started with Express and create your own web applications in no time.
About Bek
Bek is the founder and creator of BekDev. Hes him..