NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 17

How to add middleware in Node Js

Middleware functions can be used for various purposes like logging, authentication, error handling, and more.

Middleware in Node.js refers to functions that have access to the request and response objects and the next middleware function in the application's request-response cycle.

They can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack.

Link : https://chat.openai.com/c/e1ac6e22-d68a-4bbe-8e67-9a7686b37386

Here's is the Code !!

const express = require('express');
const app = express();

// Logger middleware
const loggerMiddleware = (req, res, next) => {
  console.log(`${req.method} ${req.path}`);
  next(); // Call the next middleware function
};

// Middleware to parse JSON requests
app.use(express.json());

// Use logger middleware
app.use(loggerMiddleware);

// Route handler
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Chapter 16

How to add routing in Node Js

Previous chapter

Chapter 18

How node Js connect to mongoose database?

Next chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex