Author: saqibkhan

  • Handling Query Parameters

    Query parameters can be accessed through req.query. For example:

    app.get('/search', (req, res) => {
      const query = req.query.q;
      res.send(Search results for: ${query});
    });
    

    You can access http://localhost:3000/search?q=express to see the results.

  • Template Engines

    Express can render dynamic HTML pages using template engines like EJS, Pug, or Handlebars.

    a. Installing a Template Engine

    For EJS, install it with npm:

    npm install ejs
    

    Set up EJS in app.js:

    app.set('view engine', 'ejs');
    app.set('views', path.join(__dirname, 'views'));
    

    Create a views directory and add an index.ejs file:

    <!DOCTYPE html>
    <html>
    <head>
      <title><%= title %></title>
    </head>
    <body>
      <h1>Hello, <%= name %>!</h1>
    </body>
    </html>
    

    Render the template in your route:

    app.get('/', (req, res) => {
      res.render('index', { title: 'Home Page', name: 'World' });
    });
    
  • Routing

    Express supports modular routing, which can help organize your code better.

    a. Creating Router Modules

    You can create a separate file for your routes. For example, create a file named userRoutes.js:

    const express = require('express');
    const router = express.Router();
    
    // Define routes
    router.get('/', (req, res) => {
      res.send('User List');
    });
    
    router.get('/:id', (req, res) => {
      const userId = req.params.id;
      res.send(User ID: ${userId});
    });
    
    module.exports = router;
    

    In your app.js:

    const userRoutes = require('./userRoutes');
    app.use('/users', userRoutes);
    
  • Middleware

    Middleware functions are a core feature of Express.js. They can be used to handle requests, modify request and response objects, end requests, and call the next middleware function in the stack.

    a. Creating Custom Middleware

    Here’s an example of custom middleware that logs the request method and URL:

    const logger = (req, res, next) => {
      console.log(${req.method} ${req.url});
      next(); // Call the next middleware or route handler
    };
    
    app.use(logger); // Apply middleware globally
    

    b. Error Handling Middleware

    In Express, error handling middleware functions have four arguments: err, req, res, and next. Here’s how you can use it:

    app.use((err, req, res, next) => {
      console.error(err.stack);
      res.status(500).send('Something went wrong!');
    });
    
  • Using External Middleware

    Express can use various middleware for functionalities like authentication, logging, etc. For example, to use the morgan logging library:

    npm install morgan
    

    Then, in app.js:

    const morgan = require('morgan');
    app.use(morgan('dev'));
    
  • Serving Static Files

    To serve static files like HTML, CSS, and JavaScript, use:

    app.use(express.static('public'));
    

    Create a public directory and put your static files there.

  • Error Handling

    Add an error handling middleware to catch and respond to errors:

    app.use((err, req, res, next) => {
      console.error(err.stack);
      res.status(500).send('Something broke!');
    });
    
  • Adding More Routes

    You can add more routes to handle different URLs and HTTP methods. For example:

    // Route for a user profile page
    app.get('/user/:id', (req, res) => {
      const userId = req.params.id;
      res.send(User profile for user ID: ${userId});
    });
    
  • Understanding the Code

    • const express = require('express');: Imports the Express module.
    • const app = express();: Creates an Express application.
    • app.use(express.json());: Adds middleware to parse JSON request bodies.
    • app.get('/', (req, res) => {...});: Defines a route that handles GET requests to the root URL.
    • app.post('/data', (req, res) => {...});: Defines a route that handles POST requests to /data.
    • app.listen(port, () => {...});: Starts the server and listens on the specified port.
  • Run Your Application

    Start your server using Node.js:

    codenode app.js
    

    Visit http://localhost:3000 in your browser to see “Hello World!” and use a tool like Postman or curl to test the /data POST endpoint.