10 introduction to Express node and middleware
10 introduction to Express node and middleware
10 introduction to Express node and middleware
js
Static File Serving: Effortlessly serve static files like images, CSS,
and JavaScript from a designated directory within your
application.
Node.js Integration: Express.js seamlessly integrates with the
core functionalities of Node.js, allowing you to harness the
power of asynchronous programming and event-driven
architecture.
$ mkdir myexpress
$ cd myexpress
• C:\Users\Admin\myexpress\node_modules>npm --version
express
Code Reusability
Routers promote code reusability by allowing you to define
middleware and route handlers that can be reused across different
parts of your application. You can create a router once and mount it
in multiple places if necessary.
Middleware Handling
Routers can handle middleware specific to a particular route or group
of routes. This means you can apply middleware to certain routes
without affecting the entire application. Middleware such as
authentication, logging, and input validation can be applied
selectively.
Easier Testing and Debugging
With routers, each part of your application is encapsulated, making it
easier to test and debug. You can test individual routers in isolation,
ensuring that specific routes and their associated middleware work
as expected.
node index.js
Output: We will see the following output on the terminal screen.
Server is Running
Now go to http://localhost:3000/login and
http://localhost:3000/home, we will see the output on the browser
screen.
app.get(path, (req, res, next) => {}, (req, res) => {})
Middleware functions take 3 arguments: the request object, the
response object, and the next function in the application’s request-
response cycle, i.e., two objects and one function.
"dependencies":{
"body-parser": "^1.20.2",
"express": "^4.18.2",
"ejs": "^3.1.9"
}
To serve static files such as images, CSS files, and JavaScript files, use
the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve
static assets. For more information on the options argument, see
express.static.
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
Synchronous (Blocking)
–Line by line Execution
1. Execution Flow:
• Blocking: Executes tasks sequentially, waiting for each to complete
before moving to the next.
• Non-Blocking: Initiates tasks and moves to the next without
waiting, often using callbacks or promises to handle completion.