2. Create a Node API Server


In this tutorial, we’ll use Visual Studio Code (VSC) to create an express server that can serve as an API server, test it with a browser, and copy the code to GitHub.

Create a Project Directory

  1. You should have a directory named  csci231 in the base directory of our shared Git repository.
  2. Add a sub-directory named messages-api-server to your csci231 directory.
  3. Open your messages-api-server directory in Visual Studio Code.

Organize the Project

Create the following directory structure inside the csci231-api-server directory.  We’ll add files to these directories as we progress in the course.

   > src
      > db
      > emails
      > middleware
      > messages
            > routers
            > models
      > users
            > routers
            > models

Initialize npm

Create a new node project by running the command shown below.  When you do, you will be presented with a series of prompts for information.  Press enter to accept the default values except for entry point and type.  When prompted to enter the entry point, type src/app.js and when prompted to enter the type, enter module. Press enter when asked Is this OK?

$ npm init

Install npm Packages

Run the following commands from the VSC terminal to install a set of packages in your project.

$ npm i nodemon --save-dev
$ npm i env-cmd --save-dev

$ npm i @sendgrid/mail
$ npm i bcrypt
$ npm i cors
$ npm i express
$ npm i jsonwebtoken
$ npm i mongoose
$ npm i multer
$ npm i sharp
$ npm i validator

Modify Scripts in package.json

package.json contains scripts that we can run from the command line.  Delete the test script and create two new scripts: one named start that will run the file named src/app.js (which we haven’t written yet) using node, and one named dev that will run the file named src/app.js using nodemon.

Modify the scripts property so that it reads as follows:

... 
"scripts": { 
    "start": "node src/app.js", 
    "dev": "env-cmd nodemon src/app.js" 
}, 
...

Create .env File

Create a file named .env inside your csci231-api-server directory and inside the file add the following code:

PORT=3001

We’ll use the PORT variable later to instruct express to listen for requests on port 3001 when the server is running on our laptops.

Add a .gitignore File

We don’t want git to track the files in the node_modules directory and a couple other files.  To prevent git from tracking these files create a new file named .gitignore in the project’s base directory.  Then, inside .gitignore add the following lines so that the specified directories and files are not copied to the repo.

node_modules/ 
.env 
.gitignore 
package-lock.json

Run the following command to verify the directory and files are not tracked.

$ git status

Add a Router

A router handles client requests.  Each request sent by a client specifies an endpoint, a method, and most of the time, data.  Express will direct requests to the appropriate router based on the endpoint and the method provided by the client.  

We’ll begin by creating a simple router that includes a handler for GET (the method) requests to the /user endpoint.

Create a file named user.js inside src/users/routers and add the following code.

import Router from 'express'

const router = new Router()

router.get('/user', async(req, res) => { 
    res.status(200).send("Joe User") 
}) 

export default router

When a GET /user request is received by the server, the server sends back to the client a response containing the string “Joe User” along with the status code 200.  The status code 200 indicates success.

Write a Driver

Recall in package.json the main property is set to src/app.js.  The main property specifies which JavaScript file should be initially run by node when we start the server.  Inside the src directory, create a file named app.js and add the following code to it.

import express from 'express'
import cors from 'cors'
import userRouter from './users/routers/user.js'
const app = express() 

app.use(express.json()) 
app.use(cors()) 
app.use(function (req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
}); 
app.use(userRouter) 

const port = process.env.PORT 
app.listen(port, () => { 
    console.log('Listening on port ' + port) 
})

Test the Node.js App

Now let’s start up the server using node by issuing the following command. You should see Listening on port 3001 printed to the terminal.

$ npm run dev

Now open a browser and navigate the browser to http://localhost:3001/user.  You should see Joe User displayed in the browser.

Localhost is a reserved hostname that refers to the machine on which you are working.  When you directed your browser to http://localhost:3001/user, your browser sent a GET request with the /user endpoint to port 3001 on your computer.  Since your server is listening to port 3001 for requests, your server received the request and express caused the GET /user handler in users/routers/user.js to be run.

Now change app.js so that the app send the client some other text other than “Joe User” and save the file.

Notice that nodemon automatically restarted your server.  Use the browser to verify that the app is now sending the new text.

When you’re finished experimenting, shut down the app by typing CTRL + c in the terminal.

Add Code to the Git Repository

We can now add all of the tracked files and directories to the git staging area using the following command.

$ git add .

Next we want to commit the changes to the staged files using the command below.

$ git commit -m "initial api server commit"

Now push your code to GitHub.

$ git push