DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

Node.js Crash Course - Part 6 - Express Apps

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>`)
})
Enter fullscreen mode Exit fullscreen mode
  • 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(): The get() 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');
})
Enter fullscreen mode Exit fullscreen mode

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 });
})
Enter fullscreen mode Exit fullscreen mode

4. Redirects

app.get('/about', (req, res) => {
    res.sendFile('./views/about.html', { root:__dirname });
})

app.get('/about-us', (req, res) => {
    res.redirect('/about');
})
Enter fullscreen mode Exit fullscreen mode

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 });
})
Enter fullscreen mode Exit fullscreen mode

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)=>{});
Enter fullscreen mode Exit fullscreen mode

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', ...);
Enter fullscreen mode Exit fullscreen mode

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)