├── Handling HTTP Methods,md ├── Installation.md ├── Middleware.md ├── README.md ├── Routing.md ├── Templating.md └── URL Building.md /Handling HTTP Methods,md: -------------------------------------------------------------------------------- 1 | # ExpressJS - Handling HTTP Methods 2 | 3 | HTTP methods play a crucial role in web development, determining the type of action the request wants to perform. ExpressJS simplifies the handling of various HTTP methods, such as GET, POST, PUT, DELETE, and more. In this guide, we'll explore how to handle different HTTP methods in an Express application. 4 | 5 | ## Basics of HTTP Methods in Express 6 | 7 | Express allows you to define routes based on different HTTP methods. Here's a basic example: 8 | 9 | ```javascript 10 | const express = require('express'); 11 | const app = express(); 12 | const port = 3000; 13 | 14 | // Handling GET requests 15 | app.get('/', (req, res) => { 16 | res.send('GET request received'); 17 | }); 18 | 19 | // Handling POST requests 20 | app.post('/', (req, res) => { 21 | res.send('POST request received'); 22 | }); 23 | 24 | // Handling PUT requests 25 | app.put('/', (req, res) => { 26 | res.send('PUT request received'); 27 | }); 28 | 29 | // Handling DELETE requests 30 | app.delete('/', (req, res) => { 31 | res.send('DELETE request received'); 32 | }); 33 | 34 | // Start the server 35 | app.listen(port, () => { 36 | console.log(`Server listening at http://localhost:${port}`); 37 | }); 38 | ``` 39 | 40 | In this example: 41 | 42 | - The `app.get` method handles GET requests for the root URL. 43 | - The `app.post` method handles POST requests for the root URL. 44 | - The `app.put` method handles PUT requests for the root URL. 45 | - The `app.delete` method handles DELETE requests for the root URL. 46 | 47 | ## Handling Dynamic Routes with Parameters 48 | 49 | You can handle dynamic data in your routes using parameters. For example: 50 | 51 | ```javascript 52 | // Handling GET requests with a parameter 53 | app.get('/user/:id', (req, res) => { 54 | const userId = req.params.id; 55 | res.send(`GET request for user with ID ${userId}`); 56 | }); 57 | 58 | // Handling PUT requests with a parameter 59 | app.put('/user/:id', (req, res) => { 60 | const userId = req.params.id; 61 | res.send(`PUT request to update user with ID ${userId}`); 62 | }); 63 | ``` 64 | 65 | In this example, the routes `/user/:id` handle GET and PUT requests for a user with a specific ID. 66 | 67 | ## Middleware for Handling Specific Routes 68 | 69 | Middleware functions in Express can be used to handle specific routes or types of requests. For example: 70 | 71 | ```javascript 72 | // Middleware for all routes 73 | app.use((req, res, next) => { 74 | console.log(`Received ${req.method} request for ${req.url}`); 75 | next(); 76 | }); 77 | 78 | // Middleware for specific route 79 | app.get('/protected', (req, res, next) => { 80 | // Perform authentication 81 | console.log('Authentication middleware for /protected route'); 82 | next(); 83 | }, (req, res) => { 84 | res.send('This is a protected route'); 85 | }); 86 | ``` 87 | 88 | In this example, the first middleware logs information about all incoming requests, and the second middleware is applied only to the `/protected` route, performing authentication before responding. 89 | 90 | ## Conclusion 91 | 92 | Understanding how to handle different HTTP methods in Express is essential for building robust web applications. Whether you're retrieving data with GET, creating resources with POST, updating resources with PUT, or deleting resources with DELETE, Express provides a clean and intuitive way to handle these actions. As you continue to develop with Express, explore additional features like route chaining, error handling, and more to enhance the functionality of your applications. 93 | -------------------------------------------------------------------------------- /Installation.md: -------------------------------------------------------------------------------- 1 | # ExpressJS - Installation and Creating the "Welcome to p4n" Project 2 | 3 | In this guide, we will go through the process of installing ExpressJS and creating a simple Express project named "p4n" that displays a welcome message including the phrase "codeswithpankaj." 4 | 5 | ## Step 1: Install Node.js and npm 6 | 7 | Ensure that you have Node.js and npm installed on your machine. You can download them from the official Node.js website: [Node.js Downloads](https://nodejs.org/en/download/). 8 | 9 | ## Step 2: Create a New Project 10 | 11 | Open your terminal or command prompt and create a new directory for your Express project. Navigate to the project directory using the `cd` command: 12 | 13 | ```bash 14 | mkdir p4n 15 | cd p4n 16 | ``` 17 | 18 | ## Step 3: Initialize Your Project with npm 19 | 20 | Initialize your project by running the following command: 21 | 22 | ```bash 23 | npm init -y 24 | ``` 25 | 26 | This command creates a `package.json` file with default settings. 27 | 28 | ## Step 4: Install Express 29 | 30 | Install Express in your project by running the following command: 31 | 32 | ```bash 33 | npm install express 34 | ``` 35 | 36 | ## Step 5: Create Your "Welcome to p4n" Express Program 37 | 38 | Create a file named `app.js` in your project directory. Open this file in a text editor and add the following code: 39 | 40 | ```javascript 41 | const express = require('express'); 42 | const app = express(); 43 | const port = 3000; 44 | 45 | // Define a route for the root URL 46 | app.get('/', (req, res) => { 47 | res.send('Welcome to p4n - codeswithpankaj'); 48 | }); 49 | 50 | // Start the server 51 | app.listen(port, () => { 52 | console.log(`Server listening at http://localhost:${port}`); 53 | }); 54 | ``` 55 | 56 | This code does the following: 57 | 58 | - Requires the Express module. 59 | - Creates an Express application. 60 | - Defines a route for the root URL that responds with 'Welcome to p4n - codeswithpankaj.' 61 | - Starts the server on port 3000. 62 | 63 | ## Step 6: Run Your Express Application 64 | 65 | In your terminal, run the following command to start your Express application: 66 | 67 | ```bash 68 | node app.js 69 | ``` 70 | 71 | You should see the message "Server listening at http://localhost:3000" in the terminal. 72 | 73 | Visit [http://localhost:3000](http://localhost:3000) in your web browser, and you should see the text "Welcome to p4n - codeswithpankaj" displayed on the page. 74 | 75 | Congratulations! You've successfully installed Express, set up your project, and created a basic "Welcome to p4n" Express application. This serves as a starting point for building more features and functionality into your Express projects. Explore the Express documentation for additional features and options to enhance your Express applications further. 76 | -------------------------------------------------------------------------------- /Middleware.md: -------------------------------------------------------------------------------- 1 | # ExpressJS - Understanding Middleware 2 | 3 | Middleware in ExpressJS is a powerful concept that allows you to execute functions during the request-response cycle. These functions have access to the request object (`req`), the response object (`res`), and the next middleware function in the application's request-response cycle. Middleware functions can perform various tasks, such as modifying request and response objects, executing code, handling errors, and more. 4 | 5 | ## Basics of Middleware in Express 6 | 7 | In Express, middleware is defined using functions. These functions can be applied globally to all routes or to specific routes. Middleware functions can be executed in a specific order, allowing for modular and reusable code. Here's a basic example: 8 | 9 | ```javascript 10 | const express = require('express'); 11 | const app = express(); 12 | const port = 3000; 13 | 14 | // Global middleware applied to all routes 15 | app.use((req, res, next) => { 16 | console.log('Global middleware executed'); 17 | next(); 18 | }); 19 | 20 | // Route-specific middleware 21 | app.get('/', (req, res, next) => { 22 | console.log('Middleware for the root route'); 23 | next(); 24 | }, (req, res) => { 25 | res.send('Hello, Express!'); 26 | }); 27 | 28 | // Start the server 29 | app.listen(port, () => { 30 | console.log(`Server listening at http://localhost:${port}`); 31 | }); 32 | ``` 33 | 34 | In this example: 35 | 36 | - The global middleware logs a message for every incoming request. 37 | - The route-specific middleware logs a message for requests to the root URL. 38 | 39 | ## Error Handling Middleware 40 | 41 | Middleware functions can also be used to handle errors. When an error occurs, Express skips normal route and middleware execution and jumps directly to the error-handling middleware. Here's an example: 42 | 43 | ```javascript 44 | const express = require('express'); 45 | const app = express(); 46 | const port = 3000; 47 | 48 | // Route-specific middleware 49 | app.get('/', (req, res, next) => { 50 | const error = new Error('Custom error'); 51 | next(error); 52 | }); 53 | 54 | // Error-handling middleware 55 | app.use((err, req, res, next) => { 56 | console.error(`Error: ${err.message}`); 57 | res.status(500).send('Internal Server Error'); 58 | }); 59 | 60 | // Start the server 61 | app.listen(port, () => { 62 | console.log(`Server listening at http://localhost:${port}`); 63 | }); 64 | ``` 65 | 66 | In this example, when a request is made to the root URL, the route-specific middleware generates a custom error. The error-handling middleware then logs the error message and sends a 500 Internal Server Error response. 67 | 68 | ## Third-Party Middleware 69 | 70 | Express allows you to use third-party middleware to add additional functionality to your application. Common third-party middleware includes body parsers, cookie parsers, and logging middleware. Here's an example using the `body-parser` middleware: 71 | 72 | ```javascript 73 | const express = require('express'); 74 | const bodyParser = require('body-parser'); 75 | const app = express(); 76 | const port = 3000; 77 | 78 | // Use body-parser middleware to parse JSON requests 79 | app.use(bodyParser.json()); 80 | 81 | // Route with middleware to handle JSON requests 82 | app.post('/api/data', (req, res) => { 83 | const data = req.body; 84 | res.json({ message: 'Data received', data }); 85 | }); 86 | 87 | // Start the server 88 | app.listen(port, () => { 89 | console.log(`Server listening at http://localhost:${port}`); 90 | }); 91 | ``` 92 | 93 | In this example, the `body-parser` middleware is used to parse incoming JSON requests. The route-specific middleware then handles a POST request and accesses the parsed JSON data. 94 | 95 | ## Conclusion 96 | 97 | Middleware in ExpressJS provides a flexible and modular way to enhance your application's functionality. Whether you're logging requests, handling errors, or integrating third-party functionality, middleware plays a central role in the Express ecosystem. As you continue to develop with Express, explore and leverage middleware to streamline your code and build robust web applications. 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExpressJS-tutorial-codeswithpankaj -------------------------------------------------------------------------------- /Routing.md: -------------------------------------------------------------------------------- 1 | # ExpressJS - Using Routing in the "p4n" Project 2 | 3 | ## Step 1: Update Project Structure 4 | 5 | Before diving into routing, make sure your project structure looks like this: 6 | 7 | ``` 8 | p4n/ 9 | |-- node_modules/ 10 | |-- app.js 11 | |-- package.json 12 | |-- package-lock.json 13 | ``` 14 | 15 | ## Step 2: Install Nodemon (Optional) 16 | 17 | For development convenience, you can install `nodemon` as a development dependency to automatically restart your server when changes are made. Install it by running: 18 | 19 | ```bash 20 | npm install --save-dev nodemon 21 | ``` 22 | 23 | ## Step 3: Update `package.json` Scripts 24 | 25 | Open your `package.json` file and update the "scripts" section to include a start script using `nodemon`: 26 | 27 | ```json 28 | "scripts": { 29 | "start": "nodemon app.js" 30 | } 31 | ``` 32 | 33 | Now, you can start your server using `npm start`. 34 | 35 | ## Step 4: Update `app.js` for Routing 36 | 37 | Open `app.js` in your text editor and modify it to include routing: 38 | 39 | ```javascript 40 | const express = require('express'); 41 | const app = express(); 42 | const port = 3000; 43 | 44 | // Route for the root URL 45 | app.get('/', (req, res) => { 46 | res.send('Welcome to p4n - codeswithpankaj'); 47 | }); 48 | 49 | // Route for '/about' 50 | app.get('/about', (req, res) => { 51 | res.send('About p4n - codeswithpankaj'); 52 | }); 53 | 54 | // Route with parameters 55 | app.get('/user/:username', (req, res) => { 56 | const username = req.params.username; 57 | res.send(`Hello, ${username}! Welcome to p4n - codeswithpankaj`); 58 | }); 59 | 60 | // Handling POST request 61 | app.post('/login', (req, res) => { 62 | res.send('Login Page - codeswithpankaj'); 63 | }); 64 | 65 | // Handling PUT request 66 | app.put('/user/:id', (req, res) => { 67 | const userId = req.params.id; 68 | res.send(`Updating user with ID ${userId} - codeswithpankaj`); 69 | }); 70 | 71 | // Start the server 72 | app.listen(port, () => { 73 | console.log(`Server listening at http://localhost:${port}`); 74 | }); 75 | ``` 76 | 77 | In this updated `app.js`: 78 | 79 | - The root URL `/` responds with the original welcome message. 80 | - The `/about` path responds with an "About p4n" message. 81 | - The `/user/:username` path demonstrates the use of parameters. 82 | - The `/login` path handles a POST request. 83 | - The `/user/:id` path handles a PUT request. 84 | 85 | ## Step 5: Run Your Updated Express Application 86 | 87 | Start your Express application by running: 88 | 89 | ```bash 90 | npm start 91 | ``` 92 | 93 | Visit [http://localhost:3000](http://localhost:3000) in your web browser to see the original welcome message. Explore other routes like [http://localhost:3000/about](http://localhost:3000/about) and [http://localhost:3000/user/john](http://localhost:3000/user/john) to see different responses. 94 | 95 | Congratulations! You've successfully implemented routing in the "p4n" project using ExpressJS. This is a foundation that you can build upon for more complex web applications. Feel free to experiment with additional routes, middleware, and features to enhance your Express project further. 96 | -------------------------------------------------------------------------------- /Templating.md: -------------------------------------------------------------------------------- 1 | # ExpressJS - Templating 2 | 3 | Templating in ExpressJS is a crucial aspect of building dynamic and data-driven web applications. Express supports various templating engines, allowing developers to generate HTML dynamically by rendering templates with data. In this guide, we'll explore the basics of templating in ExpressJS and demonstrate how to use the popular templating engine EJS (Embedded JavaScript). 4 | 5 | ## Setting Up EJS Templating Engine 6 | 7 | Before using EJS, you need to install it as a dependency for your Express project. Open your terminal and run: 8 | 9 | ```bash 10 | npm install ejs 11 | ``` 12 | 13 | Once installed, you can configure Express to use EJS as the templating engine in your application. 14 | 15 | ```javascript 16 | const express = require('express'); 17 | const app = express(); 18 | const port = 3000; 19 | 20 | // Set EJS as the view engine 21 | app.set('view engine', 'ejs'); 22 | 23 | // Define a route that renders an EJS template 24 | app.get('/', (req, res) => { 25 | const data = { message: 'Hello, Express with EJS!' }; 26 | res.render('index', data); 27 | }); 28 | 29 | // Start the server 30 | app.listen(port, () => { 31 | console.log(`Server listening at http://localhost:${port}`); 32 | }); 33 | ``` 34 | 35 | In this example, the `app.set('view engine', 'ejs')` line configures Express to use EJS as the templating engine. The `res.render('index', data)` line renders the `index.ejs` template with the provided data. 36 | 37 | ## Creating an EJS Template 38 | 39 | Create a new file named `views/index.ejs` in your project. This file will be the EJS template. 40 | 41 | ```html 42 | 43 | 44 | 45 | 46 | 47 | Express with EJS 48 | 49 | 50 |

<%= message %>

51 | 52 | 53 | ``` 54 | 55 | In this EJS template: 56 | 57 | - `<%= message %>` is an EJS tag that inserts the value of the `message` variable. 58 | 59 | ## Passing Data to EJS Templates 60 | 61 | As demonstrated earlier, data can be passed to EJS templates using the `res.render` method. The keys in the data object become variables accessible in the template. Here's an example with more data: 62 | 63 | ```javascript 64 | const express = require('express'); 65 | const app = express(); 66 | const port = 3000; 67 | 68 | app.set('view engine', 'ejs'); 69 | 70 | app.get('/', (req, res) => { 71 | const data = { 72 | title: 'Express with EJS', 73 | message: 'Hello, Express with EJS!', 74 | items: ['Item 1', 'Item 2', 'Item 3'] 75 | }; 76 | res.render('index', data); 77 | }); 78 | 79 | app.listen(port, () => { 80 | console.log(`Server listening at http://localhost:${port}`); 81 | }); 82 | ``` 83 | 84 | Now, you can update your `views/index.ejs` template to display the additional data: 85 | 86 | ```html 87 | 88 | 89 | 90 | 91 | 92 | <%= title %> 93 | 94 | 95 |

<%= message %>

96 | 101 | 102 | 103 | ``` 104 | 105 | In this template, `<% items.forEach(item => { %>` is an EJS tag used for looping through the `items` array, and `<%= item %>` displays each item in a list. 106 | 107 | ## Conclusion 108 | 109 | ExpressJS makes templating straightforward with the use of templating engines like EJS. Leveraging templating engines allows developers to generate dynamic content efficiently. As you explore Express further, experiment with different templating engines, such as Handlebars or Pug, and discover which one aligns best with your preferences and project requirements. 110 | -------------------------------------------------------------------------------- /URL Building.md: -------------------------------------------------------------------------------- 1 | # ExpressJS - URL Building 2 | 3 | URLs are the backbone of web applications, serving as a means of navigation and resource identification. In ExpressJS, the process of constructing URLs, often referred to as URL building or route generation, is a critical aspect of web development. In this article, we'll explore how ExpressJS facilitates URL building and provide examples to illustrate its usage. 4 | 5 | ## Basics of URL Building in Express 6 | 7 | ExpressJS simplifies the creation of URLs by providing a mechanism to define routes with dynamic parameters. These parameters can be incorporated into URLs dynamically, allowing for the construction of flexible and dynamic routes. Let's delve into the basics with an example: 8 | 9 | ```javascript 10 | const express = require('express'); 11 | const app = express(); 12 | const port = 3000; 13 | 14 | // Define a route with a dynamic parameter 15 | app.get('/users/:userId', (req, res) => { 16 | const userId = req.params.userId; 17 | res.send(`Profile page for User ID ${userId}`); 18 | }); 19 | 20 | // Start the server 21 | app.listen(port, () => { 22 | console.log(`Server listening at http://localhost:${port}`); 23 | }); 24 | ``` 25 | 26 | In this example, the route `/users/:userId` contains a dynamic parameter `userId`. When a user accesses a URL like `/users/123`, the server responds with "Profile page for User ID 123." This illustrates how Express enables the construction of URLs with dynamic components. 27 | 28 | ## Building URLs in Express 29 | 30 | Express provides a convenient method for generating URLs dynamically using the `url` method of the `request` object. This method takes the name of a route and an optional object containing parameters. Here's an example: 31 | 32 | ```javascript 33 | const express = require('express'); 34 | const app = express(); 35 | const port = 3000; 36 | 37 | app.get('/users/:userId', (req, res) => { 38 | // Get the user ID from the request parameters 39 | const userId = req.params.userId; 40 | 41 | // Build the URL for the user's profile 42 | const profileUrl = req.url('userProfile', { userId: userId }); 43 | 44 | // Send the generated URL as a response 45 | res.send(`Profile URL: ${profileUrl}`); 46 | }); 47 | 48 | // Start the server 49 | app.listen(port, () => { 50 | console.log(`Server listening at http://localhost:${port}`); 51 | }); 52 | ``` 53 | 54 | In this example, the `req.url` method is used to dynamically build the URL for the `userProfile` route. The resulting URL is then sent as part of the response. This feature is particularly useful when you want to generate URLs dynamically within your application. 55 | 56 | ## URL Building with Query Parameters 57 | 58 | Express also allows for the inclusion of query parameters in generated URLs. Query parameters are additional key-value pairs appended to the URL. Here's an example: 59 | 60 | ```javascript 61 | const express = require('express'); 62 | const app = express(); 63 | const port = 3000; 64 | 65 | app.get('/search', (req, res) => { 66 | // Get query parameters from the request 67 | const query = req.query.q || 'ExpressJS'; 68 | 69 | // Build the URL for search results with query parameters 70 | const searchUrl = req.url('searchResults', { q: query }); 71 | 72 | // Send the generated URL as a response 73 | res.send(`Search URL: ${searchUrl}`); 74 | }); 75 | 76 | // Start the server 77 | app.listen(port, () => { 78 | console.log(`Server listening at http://localhost:${port}`); 79 | }); 80 | ``` 81 | 82 | In this example, the `req.query` object is used to retrieve query parameters from the request. The `req.url` method is then employed to dynamically build a URL for search results, incorporating the query parameter. The resulting URL is sent as part of the response. 83 | 84 | ## Conclusion 85 | 86 | URL building is a fundamental aspect of web development, and ExpressJS streamlines this process with its flexible routing system. Whether you're working with dynamic parameters, generating URLs within your application, or incorporating query parameters, Express provides intuitive tools to handle URL building effectively. As you continue to explore Express, leverage these features to create dynamic and user-friendly web applications. 87 | --------------------------------------------------------------------------------