What is Node.js Middleware?
Overview
Node.js is a compatible runtime scenario for compiling JavaScript code outside of a browser. It was created on Chrome’s Javascript Engine. The Express.js functions between request and response cycles. It’s a Middleware framework for managing the routing of different web pages. A Middleware can request:
- An object
- Response object
- The next function that calls the next Middleware
Middleware syntax
app.get(path, (req, res, next) => {}, (req, res) => {})
(req, res, next) => {}: The Middleware function. It defines actions to be done before the webpage can be viewed and other functions can be called.
Creating middleware
Make sure that Node.js is installed on your computer. To create a Node.js project, we need to create a file named app.js.
The following code shows the creation of Middleware.
Example
import React from 'react';
require('./style.css');
import ReactDOM from 'react-dom';
import App from './app.js';
ReactDOM.render(
<App />,
document.getElementById('root')
);
Explanation
- Lines 1–2: We initialize two
constvalues, which specify when to use Express.js. - Line 4: Defines the port on which the program will run. In this case, it is 3000.
- Lines 5–10: The
app.getrequest fires a route handler. In this case, the handler fires on the"/"keyword, and it directs to a page where two lines between the braces are printed.