Express Middleware: Express - Js Request Response Next
Express Middleware: Express - Js Request Response Next
The above middleware is called for every request on the server. So after
every request, we will get the following message in the console.
A new request received at 1467267512545
To restrict it to a specific route (and all its subroutes), provide that route
as the first argument of [Link]().
For Example,
var express = require('express');
var app = express();
//Middleware function to log request protocol
[Link]('/things', function(req, res, next){
[Link]("A request for things received at " + [Link]());
next();
});
// Route handler that sends the response
[Link]('/things', function(req, res){
[Link]('Things');
});
[Link](3000);
Now whenever you request any subroute of '/things', only then it will log
the time
Middleware Syntax
[Link]((req, res, next) => {
// Middleware logic
next(); // Pass control to the next middleware
});
Middleware Order
Middleware is executed in the order it’s defined. Always place general
middleware (e.g., logging) before route-specific handlers.
[Link]((req, res, next) => {
[Link]('First Middleware');
next();
});
[Link]('/', (req, res) => {
[Link]('Route handler');
});
Basic Example:
const express = require('express');
const app = express(); // Middleware function to log request details
function logRequest(req, res, next) {
[Link](`${[Link]} ${[Link]}`);
next(); // Pass control to the next middleware
}
// Applicationlevel middleware
[Link](logRequest); [Link]('/', (req, res) => {
[Link]('Hello, Middleware!');
});
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
Routing
Routing refers to how an application’s endpoints (URIs) respond to client
requests. Define routing using methods of the Express app object that
correspond to HTTP methods; for example, [Link]() to handle GET
requests and [Link] to handle POST requests. You can also use
[Link]() to handle all HTTP methods and [Link]() to specify
middleware as the callback [Link] routing methods specify a
callback function (sometimes called “handler functions”) called when the
application receives a request to the specified route
(endpoint) and HTTP method. In other words, the application “listens” for
requests that match the specified route(s) and method(s), and when it
detects a match, it calls the specified callback function.
In fact, the routing methods can have more than one callback function as
arguments. With multiple callback functions, it is important to provide
next as an argument to the callback function and then call next() within
the body of the function to hand off control to the next callback.
Route definition takes the following structure:
[Link](PATH, HANDLER)
Where:
app is an instance of express.
METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
The following code is an example of a very basic route.
const express = require('express')
const app = express()
// respond with "hello world" when a GET request is made to the
homepage
[Link]('/', (req, res) => {
[Link]('hello world')
})
Route methods
A route method is derived from one of the HTTP methods, and is
attached to an instance of the express class.
The following code is an example of routes that are defined for the GET
and the POST methods to the root of the app.
// GET method route
[Link]('/', (req, res) => {
[Link]('GET request to the homepage')
})
// POST method route
[Link]('/', (req, res) => {
[Link]('POST request to the homepage')
})
Respond to a PUT request to the /user route:
[Link]('/user', (req, res) => {
[Link]('Got a PUT request at /user')
})
Respond to a DELETE request to the /user route:
[Link]('/user', (req, res) => {
[Link]('Got a DELETE request at /user')
})
```javascript
const express = require('express');
const app = express();
```
### Explanation of the Code
- `const express = require('express');` - This line imports the Express
module.
- `const app = express();` - We create an instance of an Express
application.
- `[Link]('/', (req, res) => { [Link]('Hello, World!'); });` - Here, we
define a GET route for the root URL (`/`). When this URL is accessed,
the server responds with 'Hello, World!'.
- `const PORT = [Link] || 3000;` - This sets the port the
server will listen on.
- `[Link](PORT, () => { [Link](Server is running on port
${PORT}); });` - This starts the server and listens for connections on the
specified port.
Conclusion
Understanding the GET method in [Link] is crucial for any web
developer. It allows you to handle requests efficiently and provide users
with the data they need. I encourage you to experiment with defining
your own GET routes to see the power and simplicity of [Link] in
action.
HTTP POST Method
The POST method is used to send data to the server to create a new
resource. Unlike GET requests, POST requests can include a body,
allowing you to send data such as form submissions.
```javascript
const express = require('express');
const app = express();
// POST route
[Link]('/submit-form', (req, res) => {
const formData = [Link];
// Process the form data here
[Link]('Form submitted successfully!');
});
```javascript
const express = require('express');
const app = express();
// PUT route
[Link]('/update-user/:id', (req, res) => {
const userId = [Link];
const updatedData = [Link];
// Update user data here
[Link](`User ${userId} updated successfully!`);
});
Postman:
1. Open Postman and create a new PUT request.
2. Set the URL to `[Link]
3. In the Body tab, select raw and JSON format, then add JSON data.
```json
{
"name": "Jane Doe",
"email": "[Link]@[Link]"
}
```
4. Send the request and observe the response.
Conclusion
The PUT method is crucial for updating existing resources on the server.
It ensures that the specified resource is updated with the provided data,
making it ideal for APIs that require modifications to existing data.
HTTP DELETE Method
The DELETE method is used to delete a resource from the server. It is
used to remove items from a database or files from a server.
```javascript
const express = require('express');
const app = express();
// DELETE route
[Link]('/delete-user/:id', (req, res) => {
const userId = [Link];
// Delete user data here
[Link](`User ${userId} deleted successfully!`);
});
Postman:
1. Open Postman and create a new DELETE request.
2. Set the URL to `[Link]
3. Send the request and observe the response.
Conclusion
The DELETE method is essential for removing resources from the
server. It allows for the deletion of specified resources, helping to
maintain clean and updated data on the server.
Route paths
In [Link], route paths define the endpoints for handling HTTP
requests. They can be as simple as a static string or as flexible as a
dynamic pattern with parameters and wildcards.
Route paths, in combination with a request method, define the endpoints
at which requests can be made. Route paths can be strings, string
patterns, or regular expressions.
The characters ?, +, *, and () are subsets of their regular expression
counterparts. The hyphen (-) and the dot (.) are interpreted literally by
string-based paths.
If you need to use the dollar character ($) in a path string, enclose it
escaped within ([ and ]). For example, the path string for requests at
“/data/$book”, would be “/data/([\$])book” .
Defining Routes
Routes in Express are defined using methods corresponding to HTTP
verbs like get, post, put, delete, etc.
Basic Example:
const express = require('express');
const app = express();
Multiple Parameters:
[Link]('/user/:id/book/:bookId', (req, res) => {
const { id, bookId } = [Link];
[Link](`User ${id} requested book ${bookId}`);
});
3. Optional Parameters
o Use ? to make parameters optional.
[Link]('/item/:id?', (req, res) => {
if ([Link]) {
[Link](`Item ID: ${[Link]}`);
} else {
[Link]('No item specified');
}
});
4. Wildcard Routes
o Use * as a wildcard to match any path.
[Link]('/wildcard/*', (req, res) => {
[Link]('This route matches anything after /wildcard/');
});
5. Regular Expression Routes
o Use regular expressions for advanced matching.
[Link](/a/, (req, res) => {
[Link]('This route matches paths containing the letter "a"');
});
1. Simple Path
[Link]('/about', (req, res) => {
[Link]('About Page');
});
Access URL: [Link]
Case Sensitivity
By default, route paths in Express are case-insensitive. To enforce
case sensitivity, use the caseSensitive option when initializing the app.
const express = require('express');
const app = express({ caseSensitive: true });
3. Combination of Strings
o Define routes with shared segments.
[Link]('/products/clothing', (req, res) => {
[Link]('Clothing Products');
});
/about /about
/products /products
/products/laptops /products/laptops
/user-profile /user-profile
String routes are the simplest way to define paths in Express. Use them
for fixed, well-defined URLs.
Syntax
To use a regular expression as a route path, pass it as the first argument
in the route definition:
[Link](/pattern/, (req, res) => {
[Link]('Matched a route with a regex pattern!');
});
8. Match Wildcards
Use .* to match anything.
[Link](/.*fly$/, (req, res) => {
[Link]('Matched a route ending with "fly"');
});
Matches:
/butterfly
/dragonfly
Practical Examples
Example 1: Validate IDs
Use regex to validate that an ID is numeric.
[Link](/^\/user\/\d+$/, (req, res) => {
[Link]('Valid user ID');
});
Matches:
/user/123
/user/456
Does NOT Match:
/user/abc
/user/123abc
Route handlers
We can provide multiple callback functions that behave
like middleware to handle a request. The only exception is that these
callbacks might invoke next('route') to bypass the remaining route
callbacks. We can use this mechanism to impose pre-conditions on a
route, then pass control to subsequent routes if there’s no reason to
proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or
combinations of both, as shown in the following examples.
A single callback function can handle a route. For example:
[Link]('/example/a', (req, res) => {
[Link]('Hello from A!')
})
More than one callback function can handle a route (make sure you
specify the next object). For example:
[Link]('/example/b', (req, res, next) => {
[Link]('the response will be sent by the next function ...')
next()
}, (req, res) => {
[Link]('Hello from B!')
})
An array of callback functions can handle a route. For example:
const cb0 = function (req, res, next) {
[Link]('CB0')
next()
}
Response methods
The methods on the response object (res) in the following table can
send a response to the client, and terminate the request-response cycle.
If none of these methods are called from a route handler, the client
request will be left hanging.
[Link]() :
The [Link]() function transfers the file at the path as an
‘attachment’. Typically, browsers will prompt the user to download.
Syntax:
[Link](path [, filename] [, options] [, fn])
Parameters: The filename is the name of the file which is to be
downloaded as an attachment and fn is a callback function.
Return Value: It does not return anything.
The [Link]() function in [Link] allows you to download files
from the server
const express = require('express');
const app = express();
const PORT = 3000;
[Link]() :
The [Link]() function concludes the response process and is derived
from the [Link]’s [Link]() method in the Node
core. It is employed to promptly conclude the response without including
any data.
Syntax:
[Link]([data] [, encoding])
Parameters: The default encoding is ‘utf8‘ and the data parameter is the
data with which the user wants to end the response.
Return Value: It returns an Object.
[Link]() function in [Link] is basically used to end a response
process.
const express = require('express');
const app = express();
const PORT = 3000;
// With middleware
[Link]('/user',
function (req, res, next) {
[Link]("/user called")
[Link]();
})
[Link]('/user',
function (req, res) {
[Link]("User Page")
[Link]();
});
[Link](PORT,
function (err) {
if (err) [Link](err);
[Link]("Server listening on PORT", PORT); });
[Link]() :
The [Link]() function sends a JSON response. This method sends a
response (with the correct content-type) that is the parameter converted
to a JSON string using the [Link]() method.
Syntax:
[Link]( [body] )
Parameters: The body parameter is the body that is to be sent in the
response.
Return Value: It returns an Object.
const express = require('express');
const app = express();
const PORT = 3000;
// Without middleware
[Link]('/', function (req, res) {
[Link]({ username: 'A32' });
});
[Link]() :
The [Link]() function redirects to the URL derived from the
specified path, with specified status, an integer (positive) which
corresponds to an HTTP status code. The default status is “302 Found”.
Syntax
[Link]([status] path)
Parameter: This function accepts two parameters as mentioned above
and described below:
status: This parameter holds the HTTP status code
path: This parameter describes the path.
Return Value: It returns an Object.
[Link]('/google', (req, res) => {
[Link]('[Link]
});
// Without middleware
[Link]('/', function (req, res) {
[Link]('/user');
});
// Without middleware
[Link]('/user', function (req, res) {
<html>
<head>
<title>[Link]() Demo</title>
</head>
<body>
<h2>Render function working</h2>
</body>
</html>
[Link]() :
The [Link] function is used to send a response in form of various
types of data, such as strings, objects, arrays, or buffers, and
automatically sets the appropriate Content-Type header based on the
data [Link] [Link]() function sends the HTTP response. The body
parameter can be a String or a Buffer object or an object or an Array.
Syntax:
[Link]( [body] )
Parameter: This function accepts a single parameter body that
describes the body to be sent in the response. e.g., string, array, object
etc.
Returns: It returns an Object.
[Link]() :
The [Link]() function transfers the file at the given path and it sets
the Content-Type response HTTP header field based on the filename
extension.
Syntax:
[Link](path [, options] [, fn])
Parameter: The path parameter describes the path and the options
parameter contains various properties like maxAge, root, etc and fn is
the callback function.
Returns: It returns an Object.
const express = require('express');
const app = express();
const path = require('path');
const PORT = 3000;
// Without middleware
[Link]('/', function (req, res) {
const options = {
root: [Link](__dirname)
};
[Link]() :
The [Link]() function is used to set the response HTTP status
code to statusCode and send its string representation as the response
body.
Syntax:
[Link]( statusCode )
Parameter: The statusCode parameter describes the HTTP status code.
Returns: It returns an Object.
const express = require('express');
const app = express();
const PORT = 3000;
// Without middleware
[Link]('/', function (req, res) {
// Equivalent to [Link](200).send('OK')
[Link](200);
});