Node.js Crash Course - Part 4 - Requests & Responses
Tags: node
Published: 2020-11-03 10:58:02

#1.The Request Object 
Getting the request url and request method: `req.url` & `req.method`
```
const server = http.createServer((req, res)=>{
    console.log(req.url, req.method);
})
```

#2. The Response Object 
Sending response is a three step process:
1. setting the response header
2. writing the response
3. sending the response
```
const server = http.createServer((req, res)=>{
    //Setting response header
    res.setHeader('Content-type', 'text/plain');

    //Writing the response
    res.write(`Hello, Rittwick!`);

    //Sending the response
    res.end();
})
```

In the above code we're just sending plain text. We can also send html.
```
const server = http.createServer((req, res)=>{
    console.log(req.url, req.method);
    //Setting response header to 'text/html'
    res.setHeader('Content-type', 'text/html');

    res.write('<h1>Hello! Rittwick</h1>');

    res.end();
})
```

The browse automatically adds the other tags body, html and head. We can overwrite them.
```
const server = http.createServer((req, res)=>{
    res.setHeader('Content-type', 'text/html');

    res.write('<head><title>Hello page </title></head>');
    res.write('<h1>Hello! Rittwick</h1>');

    res.end();
})
```

#3. Sending html files
```
const server = http.createServer((req, res)=>{
    res.setHeader('Content-type', 'text/html');

    fs.readFile('./views/index.html', (err, data) => {
        if(err){
            res.end();
        }else{
            res.write(data);
            res.end();
        }
    })
})
```

Instead of doing the following in two lines, we can do it in one line `res.end(data)`
```
res.write(data)
res.end()

Instead the shortcut
res.end(data)
```
When we are sending the only one data, like the above then only this shortcut can be applied.

#4. Basic Routing
```
const server = http.createServer((req, res)=>{
    res.setHeader('Content-type', 'text/html');
    let path = './views/';
    switch(req.url){
        case '/':
            path += 'index.html';
            break;
        case '/about':
            path += 'about.html';
            break;
        default:
            path += '404.html';
            break;
    }
    fs.readFile(path, (err, data) => {
        res.end(data);
    })
})
```

#5. Status Codes
Setting status codes is very easy.
`res.statusCode=<your_status_code>` for example `res.statusCode=200`

In the following code block example, status code is set according to need.
```
const server = http.createServer((req, res)=>{
    res.setHeader('Content-type', 'text/html');
    let path = './views/';
    switch(req.url){
        case '/':
            path += 'index.html';
            res.statusCode = 200;
            break;
        case '/about':
            path += 'about.html';
            res.statusCode = 200;
            break;
        default:
            path += '404.html';
            res.statusCode = 404;
            break;
    }
    fs.readFile(path, (err, data) => {
            res.end(data);
    })
})
```
Some more important points:
1. 100 range - Informative codes for browser
2. 200 range - Success codes
3. 300 range - redirection codes
4. 400 range - User side errors
5. 500 range - Server errors

Example:
* 200 - OK
* 301 - Resource moved
* 404 - Page not found
* 500 - Internal server error

#6. Redirects
Suppose my website has an established route '/about'. I wish someone who also visits to '/about-me' get redirected to '/about'. The below code does that:
* First set the statuscode to 301 `res.statusCode=301;`
* Then do `res.setHeader('Location', '/about');`
* Send the request `res.end()`
```
        case '/about':
            path += 'about.html';
            res.statusCode = 200;
            break;
        case '/about-me':
            res.statusCode = 301;
            res.setHeader('Location', '/about');
            res.end();
            break;
        default:
            path += '404.html';
            res.statusCode = 404;
            break;
```