首页 > 解决方案 > 访问从客户端传递的 nodejs 中的值的问题

问题描述

从客户端我正在传递这个项目数组

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

如下图

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

在服务器端,我访问从客户端传递的 item.id 并映射 storeItems 数组中的相应值,但在这里我得到了未定义。

# 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
  })

})

标签: javascriptnode.jsfetch

解决方案


那是因为item.id保存一个字符串并将例如“1”传递给该get方法将导致undefined映射的键是 type Number。要解决此问题,您可以将字符串转换为数字或将 item-ids 存储为字符串而不是数字:

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

或者

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

推荐阅读