Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

nodejs: http: router simple

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
    console.log(req.url, req.method);

    // Set Header Content
    res.setHeader('Content-Type', 'text/html');

    // Route
    let path = './views/';
    switch (req.url) {
        case '/':
            path += 'index.html';
            break;
        case '/about':
            path += 'about.html';
            break;
        case '/about-me':                           // Redirect to '/about'
            res.statusCode = 301;
            res.setHeader('Location', '/about');    // $$$$$ : Redirect to '/about'
            res.end();                              // Redirect to '/about'
            break;
        default:
            path += '404.html';
            break;
    }

    // Show HTML in Browser
    fs.readFile(path, (err, data) => {
        if (err) {
            console.log('Oops!!! Have error' + err);
            res.end();
        } else {
            // res.write(data);
            res.end(data);
        }

    });
});

server.listen(3000, 'localhost', () => {
    console.log('Listening for request on PORT 3000');
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: Multiply string using a for loop 
Javascript :: how to convert a title to a url slug in jquery 
Javascript :: jquery put value in table 
Javascript :: mongoose findbyidandupdate or findoneandupdate 
Javascript :: fingerprint2 
Javascript :: node rename 
Javascript :: javascript döngü dizisi 
Javascript :: set rotation and origin phaser 
Javascript :: Elementor Hide Sticky Header on Scroll Down - Show on Scroll Up 
Javascript :: phaser random triangle 
Javascript :: phaser create animation from sprite config.js 
Javascript :: phaser stagger play 1 
Javascript :: como usar variables en selector jquery 
Javascript :: js interview questions 
Javascript :: angular reactive forms bootstrap 4 
Javascript :: javascript concat two htmlcollection 
Javascript :: sadd in redis 
Javascript :: Self Invoking Functions Can Also be Used To Make Variables Global In JavaScript 
Javascript :: javascript prompts user to input 
Javascript :: filter 
Javascript :: sort array method 
Javascript :: sequelize update 
Javascript :: angular number validation 
Javascript :: vanilla js 
Javascript :: turn string into number javascript 
Javascript :: convert string to integer: 
Javascript :: why does array index start from 0 
Javascript :: javascript eliminar saltos de linea textarea 
Javascript :: Adding an item to an array 
Javascript :: how to change background color using javascript 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =