skip to Main Content

I am creating an express app that allows a user to add web projects into a list using get, post, put and delete. I have been able to write the logic for the get, delete and post requests and they work fine. I am not sure on how to allow for the user to edit the information that is in the array.

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

app.use(express.json());

let webProjects = [
    {ID: 1, TITLE: "React Game", DESCRIPTION: "Tic tac toe game created using Create React App", URL: "http://heroku/myapp/game/"},
    {ID: 2, TITLE: "Online Store", DESCRIPTION: "Online store created with HTML, CSS and Javascript.", URL: "http://git.com/myrepos/shop/index"}
]

app.get('/api', (req, res) => {
    res.send(webProjects)
})

//the :id allows to capture a dynamic value in url
app.post('/api/:id/:title/:description/:url', (req, res) => {
    const { id } = req.params;
    const { title } = req.params;
    const { description } = req.params;
    const { url } = req.params;

    const bob = {ID:id, TITLE:title, DESCRIPTION:description, URL:url}
    webProjects.push(bob)

    res.send(webProjects)
});

app.delete('/api/:id', (req, res) => {
    const { id } = Number(req.params);
    const index = webProjects.indexOf(id)
    const deleteObj = webProjects.splice(index, 1)

    res.send(`The item was successfully deleted`)

})

app.put('/api/', (res, req) => {

})



app.listen(port , () => {
    console.log('Its working')
})

4

Answers


  1. I’d claim it’s at least best practice to receive data for PUT and POST via the request body. Only put the id of the item you want to update in the url as a parameter.

    You could do something similar to this:

    app.put('/api/:id', (req, res) => {
      const projectId = parseInt(req.params.id);
      const { title, description, url } = req.body;
      const projectIndex = webProjects.findIndex(project => project.ID === projectId);
    
      if (projectIndex === -1) {
          return res.status(404).send("Project not found");
      }
    
      webProjects[projectIndex] = {
          ...webProjects[projectIndex],
          TITLE: title,
          DESCRIPTION: description,
          URL: url
      };
    
      res.send(webProjects);
    });
    
    Login or Signup to reply.
  2. Firstly bad practice is to use req.params for adding data in the post API instead you can use body for gatting the data that you want to push in the array:

      app.post('/api', (req, res) => {
        const body = req.body;
        const bob = {ID:body.id, TITLE:body.title, DESCRIPTION:body.description, 
        URL:body.url}
        webProjects.push(bob)
    
        res.send(webProjects)
    });
    

    Now about the updating first you need to find the element that you want to update. Id needs to be extracted from the params and use PUT method.

       app.put('/api/:id', (req, res) => {
          const id = parseInt(req.params.id);
          const body = req.body;
          const updateProjectIndex = webProjects.findIndex(project => project.ID === id);
        
          if (updateProjectIndex  === -1) {
              return res.status(404).send(`Project with this ${id} doesn't exist!`);
          }
        
          webProjects[updateProjectIndex] = {
              ...webProjects[updateProjectIndex],
              TITLE: body.title,
              DESCRIPTION: body.description,
              URL: body.url
          };
    
         res.send(webProjects);
    });
    
    Login or Signup to reply.
  3. Here is the working example:

    const express = require("express");
    const app = express();
    const port = 6000;
    
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    let webProjects = [
      {
        ID: 1,
        TITLE: "React Game",
        DESCRIPTION: "Tic tac toe game created using Create React App",
        URL: "http://someURL/myapp/game/",
      },
      {
        ID: 2,
        TITLE: "Online Store",
        DESCRIPTION: "Online store created with HTML, CSS and Javascript.",
        URL: "http://someURL2/shop/index",
      },
      {
        ID: 3,
        TITLE: "Online Store",
        DESCRIPTION: "Online store created with HTML, CSS and Angular.",
        URL: "http://someURL3/shop2/index",
      },
    ];
    
    app.get("/api", (req, res) => {
      res.send(webProjects);
    });
    
    app.put("/api/:id", (req, res) => {
      const id = req.params.id;
    
      const newData = req.body;
      let tempIndex = webProjects.findIndex((elem) => elem.ID == id);
      //database ID of data which is going to be updated
      let dB_ID = webProjects[tempIndex].ID;
    
      if (tempIndex > -1) {
        webProjects[tempIndex] = {
          ID: dB_ID,
          TITLE: newData.TITLE,
          DESCRIPTION: newData.DESCRIPTION,
          URL: newData.URL,
        };
    
        return res.status(200).json(webProjects[tempIndex]);
      } 
    
        return res.status(404).json({
          msg: "ID does not found!",
        });
    });
    
    app.listen(port, () => {
      console.log("server is listening on : " + port);
    });
    
    Login or Signup to reply.
  4. You should also consider to update your delete route.
    Otherwise you wolud always delete the last Project in the array.

    app.delete('/api/:id', (req, res) => {
      const projectId = parseInt(req.params.id);
      const projectIndex = webProjects.findIndex(project => project.ID === projectId);
    
      if (projectIndex === -1) {
          return res.status(404).send("Project not found");
      }
    
      webProjects.splice(projectIndex,1);
    //res.send(`The item was successfully deleted`)
      res.send(webProjects);
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search