Saturday, July 4, 2020

How to create Node JS Basic Routing

1. Reference: https://github.com/acad1. Create project folder
------------------------
malex@WINDOWS-1J3BS7A MINGW64 /
$ cd ~

malex@WINDOWS-1J3BS7A MINGW64 ~
$ cd node-tutorial/

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial
$ ls -l
total 8
drwxr-xr-x 1 malex 197121 0 Jul  4 11:56 node-pgsql/
drwxr-xr-x 1 malex 197121 0 Jul  4 12:35 node-rest-shop/

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial
$ mkdir -p node-rest-shop-basic-router/api/routes

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial
$ cd node-rest-shop-basic-router/

2. Initialize the project
-------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (rest-shop-basic-router)
version: (1.0.0)
description: A Node.js RESTful API Tutorial Project (Build a simple shop API)
entry point: (index.js) server.js
test command:
git repository:
keywords:
author: Alex Madriaga
license: (ISC)
About to write to C:\Users\malex\node-tutorial\node-rest-shop-basic-router\packa
ge.json:

{
  "name": "rest-shop-basic-router",
  "version": "1.0.0",
  "description": "A Node.js RESTful API Tutorial Project (Build a simple shop API)",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Alex Madriaga",
  "license": "ISC"
}


Is this OK? (yes) yes

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$

3. Create the server.js
-----------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ touch server.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ vi server.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ cat server.js

const app = require('./app');
const port = process.env.PORT || 3700;

// 0. default root
app.get("/",async (req,res, next) => {
    try{
      res.send("Welcome to Node REST Shop Basic Router Application");
    } catch(error){
       console.error(error.message);
    }
});

app.listen(port,()=> {
    console.log("Server is listening on port :",port);
});

4. Create the app.js
-----------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ touch app.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ vi app.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ cat app.js

const express = require("express");
const app = express();
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders.js');

app.use('/products', productRoutes);
app.use('/orders', orderRoutes);

module.exports = app;

5. Create orders routes
-----------------------

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ touch api/routes/orders.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ vi api/routes/orders.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ cat api/routes/orders.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'Orders were fetched'
    });
});

router.post('/', (req, res, next) => {
    res.status(201).json({
        message: 'Order was created'
    });
});

router.get('/:orderId', (req, res, next) => {
    res.status(200).json({
        message: 'Order details',
        orderId: req.params.orderId
    });
});

router.delete('/:orderId', (req, res, next) => {
    res.status(200).json({
        message: 'Order deleted',
        orderId: req.params.orderId
    });
});

module.exports = router;

6. Create products routes
-------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ touch api/routes/products.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ vi api/routes/products.js

malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ cat api/routes/products.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'Handling GET requests to /products'
    });
});

router.post('/', (req, res, next) => {
    res.status(201).json({
        message: 'Handling POST requests to /products'
    });
});

router.get('/:productId', (req, res, next) => {
    const id = req.params.productId;
    if (id === 'special') {
        res.status(200).json({
            message: 'You discovered the special ID',
            id: id
        });
    } else {
        res.status(200).json({
            message: 'You passed an ID'
        });
    }
});

router.patch('/:productId', (req, res, next) => {
    res.status(200).json({
        message: 'Updated product!'
    });
});

router.delete('/:productId', (req, res, next) => {
    res.status(200).json({
        message: 'Deleted product!'
    });
});

module.exports = router;

7. Install express module
-------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ npm i express -s
+ express@4.17.1
added 50 packages from 37 contributors and audited 50 packages in 2.131s
found 0 vulnerabilities

8. Install morgan module
-------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ npm i morgan -s
+ morgan@1.10.0
added 4 packages from 2 contributors and audited 54 packages in 1.286s
found 0 vulnerabilities

9. Install nodemon module
-------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ npm i nodemon -s
+ nodemon@2.0.4
added 118 packages from 54 contributors and audited 173 packages in 7.435s

8 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities


10. View updated package.json
----------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-router
$ cat package.json

{
  "name": "rest-shop-basic-router",
  "version": "1.0.0",
  "description": "A Node.js RESTful API Tutorial Project (Build a simple shop API)",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Alex Madriaga",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.4"
  }
}


11. Run the node js application
-------------------------------
malex@WINDOWS-1J3BS7A MINGW64 ~/node-tutorial/node-rest-shop-basic-rc-router
$ nodemon index.js

12. Open browser at htpp://localhost:3700
-----------------------------------------

No comments:

Post a Comment