Routes

app.js

const express = require('express');
const app = express();

app.use('/add-product', (req, res, next) => {
    console.log('in the another middleware');
    res.send('<h1>The Add product page</h1>');
});

app.use('/', (req, res, next) => {
    console.log('in the another middleware');
    res.send('<h1>Hello from Express !</h1>');
});

app.listen(3000);



Routes - example with form

We need to install body-parser for parsing incoming requests.

npm install --save body-parser



app.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({exteneded: false}));

app.get('/add-product', (req, res, next) => {
    res.send('<form action="/product" method="POST"><input type="text" name="title"><button type="submit">Add product</button></form>');
});

//this will trigger for only POST requests
app.post('/product', (req, res, next) => {
    console.log(req.body);  //req.body is available because of using bodyParser
    res.redirect('/');
});

app.use('/', (req, res, next) => {
    res.send('<h1>Hello from Express !</h1>');
});

app.listen(3000);




Routes - using Router and Path - Serving HTML pages

Typically you dont want to have all the code in single file. Using Router you can split routes code into separate files.

-routes
    |
    |---admin.js
    |---shop.js
-views
    |
    |---shop.html
    |---add-product.html
-util
    |
    |---path.js
-public
    |
    |---css
        |
        |---main.css
-app.js



util/path.js

const path = require('path');
module.exports = path.dirname(process.mainModule.filename);



routes/admin.js

const path = require('path');
const express = require('express');
const router = express.Router()
const rootDir = require('../util/path'); //if we want to use path to dirname above

const products = [];

router.get('/add-product', (req, res, next) => {
    res.sendFile(path.join(__dirname,'../', 'views', 'add-product.html'));
    //__dirname return routes folder, then we need to go up one level, then to views, where is shop.html

    //OR - using rootDir and  util/path.js
    //res.sendFile(path.join(rootDir, 'views', 'add-product.html'));
});

//this will trigger for only POST requests
router.post('/add-product', (req, res, next) => {
    console.log(req.body);  //req.body is available because of using bodyParser
    products.push({ title: req.body.title });
    res.redirect('/');
});

exports.routes = router;
exports.products = products;



routes/shop.js

const path = require('path');
const express = require('express');
const router = express.Router();
const adminData = require('./admin');

router.get('/', (req, res, next) => {
    //res.send('<h1>Hello from Express !</h1>');
    res.sendFile(path.join(__dirname, '../', 'views', 'shop.html'));
    //__dirname return routes folder, then we need to go up one level, then to views, where is shop.html
});
module.exports = router;



views/add-product.html

<!DOCTYPE html>
<html>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="/">Shop</a></li>
                <li><a href="/admin/add-product">Add product</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <form action="/admin/add-product" method="post">
            <input type="text" name="title">
            <button type="submit">Add product</button>
        </form>
    </main>
</body>
</html>



views/404.html

<!DOCTYPE html>
<html>
<body>
    <h1>Page not found</h1>
</body>
</html>



views/shop.html

<!DOCTYPE html>
<html>
<head>
    <!-- we are using express.static in app.js to serve static css file from public dir -->
    <link rel="stylesheet" href="/css/main.css">
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="/">Shop</a></li>
                <li><a href="/admin/add-product">Add product</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <h1>My Products</h1>
        <p>List of all products...</p>
    </main>
</body>
</html>



app.js

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(bodyParser.urlencoded({exteneded: false}));

//add this to make public folder available to serve static files, like css
app.use(express.static(path.joing(__dirname, 'public')));

app.use('/admin', adminData.routes);
app.use(shopRoutes);

//404 error page, when i make request to path which doesnt exists
app.use((req, res, next) => {
    res.status(404).sendFile(path.joing(__dirname,'views','404.html'));
});

app.listen(3000);