0% found this document useful (0 votes)
2 views7 pages

creating custom middleware

Uploaded by

sumathi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
2 views7 pages

creating custom middleware

Uploaded by

sumathi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 7

Simple web server using Express

const express = require("express"); //require express


const app = express(); //create the app

app.get("/", (req, res) => {


res.send(`Hello World`);
}); // send a response to the client

app.listen(8000, () => {
console.log("App has started and running ");
}); // listen for connection to the app
When the express() function is called, it returns an object, commonly referred
to as app.

This object provides methods for handling HTTP request routing, configuring
middleware, rendering HTML views, and registering template engines.

The app.get() method defines a route by specifying a path and a callback


function as its arguments.

The callback function is executed whenever a client makes an HTTP GET


request to that path.

It receives two arguments: the request object and the response object.

The response object has a send method (res.send()), which is used to send a
response back to the client. In this case, it sends the string "Hello World."

Finally, app.listen() starts the server and listens for incoming connection
Creating Custom Middleware
• Define a function that takes the Request object
as the first argument, the Response object as the
second argument, and a third argument called
next
• The next parameter is a function provided by the
middleware framework, which points to the next
middleware to be executed. Make sure to call
next() before exiting the custom function;
otherwise, the handler will not be invoked.
example
• queryRemover(): Removes the query string
from the URL before passing it to the handler
var express = require('express');
var app = express();

function queryRemover(req, res, next) {


console.log("\nBefore URL: ");
console.log(req.url);

req.url = req.url.split('?')[0]; // This removes the query string from the URL by splitting the string at '?' and
keeping only the part before it.

console.log("\nAfter URL: ");


console.log(req.url);

next(); // Call the next middleware or route handler


}

app.use(queryRemover); // Use queryRemover middleware for all incoming requests

app.get('/no/query', function(req, res) {


res.send("test"); // Send a response "test" when this route is matched
});

app.listen(80); // Start the server and listen on port 80

You might also like