Friday: Quiz: Creating CRUD Operations with Node.js Copy

Introduction

In this assignment you will be creating a crud operation using node js express server (without database for now) and this assignment will be like a guided tutorial that will guide you through the steps :

Instructions

1. Create and Initialize the Project

  • create a directory to hold your application, and make that your working directory.
$ mkdir myapp
$ cd myapp
  • Use the npm init command to create a package.json file for your application myapp
$ npm init -y

2. Add Express

  • Now install Express in the myapp directory and save it in the dependencies list.
$ npm install express
  • Next you need to install nodemon as a development dependency to make your life easier and restart the server each time you do modifications.
npm install --save-dev nodemon

Now that express & nodemon were installed, your package.json file should look as follows:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }

Now let’s move on to the next step and start Coding 👩🏻‍💻👨🏻‍💻

3. Create Express Server

  • First step in your myapp root directory create a server.js file (ofc the name is not important- can be of any name) Your project should look sth like this

  • In your server.js file require express and use it to create an express app like so
const express = require('express')
const app = express()
  • By this point you should know that the data will be transferred via network in JSON format, so you need to parse it each time you will use it, for that we need an alternative method that will parse all the data received automatically instead of parsing it each time (cuz we are lazy) and this method is express.json()
app.use(express.json());
  • Now Create routes and listen on a specific port

you can create a default route to test your app by

app.get('/', (req, res) => {
  res.send('Hello World!')
})
  • make your server listen on a port number ( we will use port 3000 for this example )
app.listen(3000)

Put all together your code in server.js file should look like this

const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.listen(3000)

4. Access the app in the browser

  • To start the application, you need to run your server for that
  • create a script in the package.json to run the server with nodemon
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"nodemon server.js"
  },
  • Now you can start your server by running : npm start or npm run start in terminal
  • Now that the server is running, you can access it in your browser. Go to http://localhost:3000/.and you should see the Hello World! message
Now let’s work on the RESTFUL API & CRUD operation
  • But first since you are not using any database you will create a mockup data in an array (in server.js)

  • Next you will start by creating a route for a get request that will send the list of todos as a response from the server.
How to implement the GET request ? let’s see…
  • The first parameter is the endpoint, in our example it’s “/todos”.
  • The second parameter is a callback, in our example it’s an arrow function with request and response (req, res) parameters,
  • in the function block we will use the res.send method to send back the todos array as a response

  • What do you think if you use Postman to test if your endpoint is working or not 🤔
  • This can be done simply by creating new app, setting the method, adding the url & the endpoint, and click send you can see the response in the result section and test any request

Moving on let’s see how can we add a new todo using http Post method
  • to create a route POST request the rout of “/todo/create”
  • In this request you need to handle the req.body which is the data sent from the front end side.
  • Then push it to the array of todos and generating a unique id to it
  • The last thing is to send back a response message to the front end, to confirm the success of your insertion / creating & adding new todo

so your code will look something like this :

Let’s test the work on Postman

  • To test this it will be similar as testing the get request (but instead you need to set the method as post and use the post endpoint)
  • In addition, you need to add the body of the request in the JSON format :

DELETE request
  • Next we have the DELETE request which gonna contain the parameter as part of the url.
  • so your rout will be “/todo/delete/:id”
  • The :id means that the last part of the endpoint will be the params of the request ,and the id of the element that should be deleted
  • To get the id from the parameter you will be using req.params.id
  • And then you need just to find the element in the array of todos and delete it.
  • Then send back a message of deleted.

so your code will look like this:

Testing The work on Postman

Now, how about you try it by yourself 😉

PUT request
  • Finally you need to use PUT request to update a specific todo,
  • You can use the route of “/todo/update/:id”
  • This request is gonna be for updating an element in the array of todos.
  • like the delete request the put request will need to have params for the id of the element to be updated
  • but also you need to have a request body to get the new value of that element,
  • and for the logic it will be similar to the delete request except that now instead of deleting the element you will update it.
  • then a message response with “updated” text will be send back to the frontend.

so the code will be like so

I think we will give you the chance to do this part by yourself 💪🏻 and you can tell us how the code will be looking like in your gitHub repo 😉

  • Do not forget to test your work on postman
GitHub :
  • Push your solution.
  • Add your instructors as collaborators
  • Then submit your repo link in the quiz submission section.