Overview

Skill Level: Beginner

This tutorial will go through setting up a sample server in NodeJS that accepts GET requests and POST requests. I will be demoing it on Mac

Ingredients

  1. Postman
  2. NodeJS (Will detail installation)
  3. Basic understanding of terminal

Step-by-step

  1. Installation

    1. Go to www.nodejs.org
    2. Download the Recommended version via the left download box
    3. Install the application via the downloaded file
    4. Open up your terminal and run these commands
    5. node -v
    6. npm -v

       

    7. You should see successful output of both of these commands in your terminal
  2. Build a Sample Application to understand the basic routing of an express server.

    1. Create a folder on your desktop called Node Sample App
    2. Inside the folder create a file named app.js
    3. Open up app.js and add this code
      1. const express = require('express'); //Require express, the lightweight server module
        const bodyParser = require("body-parser"); //Require bodyparser, a tool necessary to parse POST values

        //Initialize the app values
        const app = express();
        //Allow the app to parse values
        app.use(bodyParser.urlencoded({
        extended: true
        }));
        app.use(bodyParser.json());


        app.get('/', (req, res) => res.send('Hello World. This is a GET request URL'))

        app.get('/sampleGET/:name', function (req, res){
        var name = req.params.name; //GET Parameters are passed in with this format
        res.send('Hello World. This is a GET request URL with a parameter passed in URL. The Name is ' + name);
        });


        app.post('/samplePOST', function (req, res){
        var name = req.body.name; //POST parameters are passed in with this format
        res.send('Hello World. This is a POST request URL with a parameter passed in body. The Name is ' + name);
        })



        app.listen(3000, () => console.log('Example app listening on port 3000!'))
    4. Open up your terminal and navigate to the Node Sample App folder
      1. Navigate using ls and cd to the folder
    5. Run this command to install our express module
      npm install express
    6. Run this command to build our package.json
      npm init
      1. name – node_sample_app
      2. enter
      3. enter
      4. enter
      5. test command – node app.js
      6. enter
      7. enter
      8. enter
      9. enter
      10. enter
  3. Testing

    1. Run this command
      1. npm test
    2. The console should show the server is running (“Example App listening on port 3000”)
    3. We have three URLs
      1. http://localhost:3000/
      2. http://localhost:3000/sampleGET/zach
      3. http://localhost:3000/samplePOST
    4. Navigate to URL 1 and 2 via your webbrowser
    5. Open up Postman and build a requst like seen below. Then click send.
      1. Screen-Shot-2018-03-24-at-2.14.29-PM
      2. You will see the end result on the bottom

Join The Discussion