1. Installing Express
npm install express
will install the required 'express' package locally.
2. Creating Express App
const express = require('express');
const app = express();
app.listen(3000);
app.get('/', (req, res) => {
res.send(`<p>this is a very nice paragraph of index page</p>`)
})
-
const app = express()
: This is our express app -
app.listen(3000)
: By this line our app listens to port number 3000, and automatically the host is localhost -
app.get()
: Theget()
method is used to handle a get request -
res.send()
: automatically detects the content header, and automatically assigns the correct status code. We manually can also do that, but not mandatory.
3. Routing and HTML Pages
app.get('/', (req, res) => {
res.sendFile('./views/index.html');
})
app.get('/about', (req, res) => {
res.sendFile('./views/about.html');
})
But this is not going to work.
The file path in sendFile
should be a absolute path OR if it is a relative path then we have to specify the root path. The above do not work and the following code works.
app.get('/', (req, res) => {
res.sendFile('./views/index.html', { root:__dirname });
})
app.get('/about', (req, res) => {
res.sendFile('./views/about.html', { root:__dirname });
})
4. Redirects
app.get('/about', (req, res) => {
res.sendFile('./views/about.html', { root:__dirname });
})
app.get('/about-us', (req, res) => {
res.redirect('/about');
})
res.redirect('<route>')
this automatically sets the content header and status code and redirects to the redirected route.
5. 404 Pages
app.get('/', (req, res) => {
...
})
app.get('/about', (req, res) => {
...
})
app.use((req, res)=>{
res.sendFile('./views/404.html', { root:__dirname });
})
app.use()
will be fired for every request if it reaches till this function.
Express executes the file top to down.
app.get('/', ...);
app.get('/about', ...);
app.use((rq,rs)=>{});
first it will check app.get('/'),
if not match, then app.get('/about'),
if not match, then app.use();
So where we place the app.use()
is very important. For example:
app.get('/', ...);
app.use((rq,rs)=>{});
app.get('/about', ...);
In the above code block '/about' route will never be encountered. As soon as the request will reach app.use()
this will return the response
Top comments (0)