Getting Started with Express JS
Last Updated :
12 Mar, 2024
Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice among developers. Express is released as free and open-source software under the MIT License.
Prerequisites:
Installing Express JS:
Step 1: Create a project directory:
- Open your terminal or command prompt.
- Navigate to your desired workspace using the cd command.
- Create a new directory for your project:
mkdir express-app
- Change into the newly created directory:
cd express-app
Step 2: Initialize a package.json file:
- Run below to create a basic package.json file to manage your project's dependencies.
npm init -y
Step 3: Install Express:
- Install Express as a dependency using npm:
npm install express
Running a simple web server in Express JS:
- require('express'): Imports the Express module.
- const app = express(): Creates an Express application instance, which serves as the foundation for building your web application.
- app.listen(port, callback): Starts the server and listens for requests on the specified port.
- process.env.PORT: Checks for an environment variable named PORT that might be set to a specific port number.
- callback: An optional function that is called when the server starts successfully.
JavaScript
const express = require('express');
const app = express();
// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Adding Routes for Handling request in Express JS:
- Express provides methods to define routes, which map specific URL paths to corresponding server-side functions (handlers) that handle incoming requests.
- These methods come in different flavors for various HTTP methods (GET, POST, PUT, DELETE, etc.):
- app.get(path, handler): Defines a route that handles GET requests to the specified path. The handler function is called with two arguments:
- req: The request object containing information sent by the client (e.g., headers, parameters, body).
Now, when you refresh your browser, you should see "Hello from my Express app!" displayed.
- res: The response object used to send a response back to the client (e.g., send data, set status codes).
- You can use other HTTP methods like app.post, app.put, app.delete, etc., following the same syntax.
JavaScript
const express = require('express');
const app = express();
// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
// Code to handle GET requests to the root path ('/')
res.send('Hello from my Express app!');
});
app.post('/users', (req, res) => {
// Code to handle POST requests to the '/users' path
// (e.g., for creating a new user)
res.send('User creation successful!');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Adding Parameters to Routes in Express JS:
You can capture dynamic values from URLs using parameters:
- :id is a placeholder for a dynamic value.
- req.params: An object containing the captured parameter values.
Navigate to http://localhost:3000/users/<id> (or the port you specified). You should see "User with ID: <Id you mentioned in the URL >" is displayed.
JavaScript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000; // Use environment variable or default to port 3000
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Access the parameter value
res.send(`User with ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Modularizing Routes with Express Router:
As your application grows, managing routes in a single file can become cumbersome. Express Router allows you to create modular route handlers:
Create a separate file for routes (e.g., routes.js):
JavaScript
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello from Express routes!');
});
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Access the parameter value
res.send(`User with ID: ${userId} from routes`);
});
module.exports = router;
Importing and using the router in your main app (app.js):
JavaScript
const express = require('express');
const app = express();
// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;
// Import the router
const routes = require('./routes');
// Use the router for all paths starting with '/'
app.use('/', routes);
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Adding Middleware for Processing Requests in Express JS:
Middleware are functions that have access to incoming requests and outgoing responses in your Express application. They allow you to perform common tasks across multiple routes or the entire application, such as logging, authentication, and error handling.
Middleware is registered using the app.use() method. The order of middleware execution matters: they are called in the order they are registered.
Here's an example of a middleware function that logs incoming requests:
Middleware can not only log requests but also modify them before they reach the route handler. For example, a middleware can be used to parse incoming JSON data:
app.use(express.json()); // Parse incoming JSON requests automatically
JavaScript
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware or route handler
});
Adding Error Handling Middleware in Express JS:
Error Handling is crucial for a robust application. Express provides a way to catch errors thrown in your application code or middleware. Here's an example of error handling middleware:
JavaScript
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error for debugging
res.status(500).send('Internal Server Error'); // Send a generic error response
});
This middleware is a catch-all for any errors that haven't been handled by specific route handlers. It logs the error and sends a generic error response to the client.
Place error handling middleware at the bottom of your app.use() chain, after all other middleware and route handlers, so it catches unhandled errors. Consider providing more specific error messages for different error types in a production environment.
By implementing middleware effectively, you can streamline common tasks, improve the maintainability of your code, and create a more robust and user-friendly web application.
Similar Reads
How to use get parameter in Express.js ?
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
Express.js res.set() Function
The res.set() function is used to set the response HTTP header field to value. To set multiple fields at once, pass an object as the parameter.Syntax: res.set(field [, value])Parameters: The field parameter is the name of the field and the value parameter is the value assigned to the field parameter
2 min read
Express.js res.type() Function
The res.type() function is used to set the Content-Type HTTP header to the MIME type determined by the mime.lookup() function for the specified type. Syntax: res.type( type ) Parameters: The type parameter describes the MIME type. Return Value: It returns an Object. Installation of the express mod
2 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read
Express.js router.route() Function
The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors. Syntax:router.route( path )Parameter: The path parameter holds
2 min read
What is Routing in Express?
In web applications, without routing it becomes difficult for the developers to handle multiple different requests because they have to manually process each URL request in a single function this problem was solved by the express router which provides a structured way to map different requests to th
5 min read
Express.js res.redirect() Function
In Express.js, the res.redirect() function is one of the most commonly used methods to handle redirection in a web application. This method is part of the response object (res), and it allows you to send an HTTP redirect to the client, telling it to navigate to a different URL.What is Redirection?In
4 min read
Express JS HTTP Methods
In this article, we are going to learn about the different HTTP methods of Express JS. HTTP methods are hypertext transfer protocol methods to exchange data between two or more layers of an application using a request and response cycle.In web development, we use HTTP methods to connect client-side
4 min read
Express.js res.get() Function
The res.get() function returns the HTTP response header specified by the field. The match is case-insensitive. Syntax:Â res.get( field ) Parameter: The field parameter describes the name of the field. Return Value: It returns an Object. Installation of the express module:Â You can visit the link to
2 min read
Express.js req.get() Function
The req.get() function returns the specified HTTP request header field which is a case-insensitive match and the Referrer and Referrer fields are interchangeable. Syntax:req.get( field )Parameter: The field parameter specifies the HTTP request header field. Return Value: String. Installation of the
2 min read