javascript - 访问从客户端传递的 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
})
})
解决方案
那是因为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" }],
])
推荐阅读
- linux - Linux上的cd(更改目录)命令
- google-classroom - 当 Google Classrom 为参加课程的教师列出 courseWork API 时收到 403
- angular - 如果隐藏元素,如何检测 Angular 中的屏幕尺寸是否发生变化?
- spring-integration - 没有数据源轮询的 MessageChannelPartionHandler 堆栈跟踪
- r-markdown - tinytex:::is_tinytex() 返回 true,但我仍然无法从 rmarkdown 编织到 PDF
- sql - 如何将表拆分为具有限制行数的多个部分?
- multipartform-data - 上传到 Next.js API 时损坏的图像
- curl - cURL - 如何使用内部 wsdl 成功校准(脚本)
- php - 使用 mb_substr php 时如何避免一个元素大于另一个元素
- antlr - 在 Xtext/ANTLR 中终止多行文本块