Search code examples
javascriptnode.jsfetch

Issues in accessing values in nodejs passed from client side


from client side I am passing this items array

{ id: '1', quantity: '1' }
{ id: '2', quantity: '1' }

like shown below

# Javascript
fetch("/purchase", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({
      items: items,
    }),
  })

In the server side I access the item.id which is passed from the client side and map the corresponding value in the storeItems array but here I am getting undefined.

# Nodejs
const storeItems = new Map([
  [1, { price: 10000, name: "Assessment" }],
  [2, { price: 20000, name: "Therapy" }],
])


app.post("/purchase", (req, res) => { 

  
  req.body.items.forEach(function(item){
    console.log(item.id)  //this works   
    const storeItem = storeItems.get(item.id)
    console.log(storeItem)   //getting undefined
  })

})


Solution

  • That's because item.id holds a string and passing e.g. "1" to the get method will result in undefined as the map's keys are of type Number. To fix this you can either convert the string to a number or store the item-ids as a string instead of a number:

    const storeItem = storeItems.get(Number.parseInt(item.id));
    

    OR

    const storeItems = new Map([
      ["1", { price: 10000, name: "Assessment" }],
      ["2", { price: 20000, name: "Therapy" }],
    ])