U4 02 Express JS
U4 02 Express JS
U4 02 Express JS
UNIT-IV
Express JS
What is Express JS?
Fast
https://expressjs.com/
unopinionated,
minimalist
web framework
for Node.js
Also, it can inject data into HTML template at client side and produce the final
HTML.
A Template Engine enables you to use static template files in your application.
At runtime, the template engine replaces variables in a template file with actual
values, and transforms the template into an HTML file sent to the client.
Template engine makes you able to use static template files in your
view engine: It specifies the template engine that you use. For example, to
create an app.js file and a views folder in the root folder. Inside the views
folder, create folder pages.
Faster performance.
Route paths
which requests can be made. Route paths can be strings, string patterns, or
regular expressions.
Defining Routes
This route path will match requests to the root route, /.
app.get('/', (req, res) => {
res.send('root')
})
This route path will match requests to /about.
app.get('/about', (req, res) => {
res.send('about')
})
This route path will match requests to /random.text.
app.get('/random.text', (req, res) => {
res.send('random.text')
})
Route paths based on string patterns.
This route path will match acd and abcd.
app.get('/ab?cd', (req, res) => {
res.send('ab?cd')
})
This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', (req, res) => {
res.send('ab+cd')
})
This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.
app.get('/ab*cd', (req, res) => {
res.send('ab*cd')
})
Route paths based on regular expressions
This route path will match anything with an “a” in it.
app.get(/a/, (req, res) => {
res.send('/a/')
})
This route path will match butterfly and dragonfly, but not butterflyman,
dragonflyman, and so on.
app.get(/.*fly$/, (req, res) => {
res.send('/.*fly$/')
})
Route parameters
Route parameters are named URL segments that are used to capture the values
The captured values are populated in the req.params object, with the name of the
res.sendStatus() Set the response status code and send its string representation as the response body.
Defining Routes-index.html
Application-level middleware
Router-level middleware
Error-handling middleware
Built-in middleware
Third-party middleware
Middleware in Express
The app.use() function is used to mount the specified middleware
function(s) at the path which is being specified. It is mostly used to set up
middleware for your application.
Syntax:
app.use(path, callback)