POST请求正文中的数组不可迭代



我正在为我的网站构建一个私有的API,并试图通过API端点接收传递给程序的数据。我正在尝试迭代存储在键处的数组中的所有项。向API端点发出的POST请求的主体形状如下:

{
"tracked": [
{
"categoryId": 100,
"categoryName": "Cars",
"items": [
{
"item": "Red Car",
"itemId": "",
"limit": 1
},
{
"item": "Blue Car",
"itemId": "",
"limit": 1
},
]
},
{
"categoryId": 200,
"categoryName": "Trucks",
"items": [
{
"item": "Red Truck",
"itemId": "",
"limit": 1
},
{
"item": "Blue Truck",
"itemId": "",
"limit": 1
},
]
}
]
}

我的问题是:当试图在键"处迭代数组时;被跟踪的";我的应用程序抛出一个异常"TypeError:tracked.tracked不可迭代。为什么会这样,我该如何解决这个问题?tracked处的值显然是一个数组。以下是不起作用的代码。

import * as functions from "firebase-functions";
import * as express from 'express'
// init express app
const app = express()
// my routings
const apiRoute = require("./api")
// enable json parsing
app.use(express.json())
// add routes to the express app.
app.use("/api", apiRoute)
exports.api = functions.https.onRequest(app)
router.route('/data/tracked').post( async (req, res) => {

const tracked = req.body.tracked as Tracked
const response = postTracked(tracked)
res.status(200).send(response)
})
/**
* Ingests a json of tracked items and categorys formatted as type Tracked
* @param tracked json of categorys and their respective items being tracked
* @returns response with indicated success.
*/
export const postTracked = async (tracked: Tracked) => {
// set item id's in ingested json.
const newTracked: Tracked = {
tracked: [],
}
for (const cat of tracked.tracked) {
const category: Category = {
categoryId: cat.categoryId,
categoryName: cat.categoryName,
items: []
}
for (const itm of cat.items) {
const itemId = `${cat.categoryId}-${generateRandomString(5)}`
category.items.push({
item: itm.item,
itemId: itemId,
limit: itm.limit,  
} as Item)
}
newTracked.tracked.push(category);

}
// update the tracked list.
await db.collection('trackers').doc('eBay').set(tracked, {merge: true})
return responseBuilder(true, (await db.collection('trackers').doc('eBay').get()).data())
}

这个函数以前在时工作,而不是使用express,只是firebase.functions.onCall,如下所示。

const ingestTrackedJSON = functions.https.onCall(async (data, context) => {
// set item id's in ingested json.
const tracked: TrackedItems = {
tracked: [],
}
for (const cat of ingest.tracked) {
const category: Category = {
categoryId: cat.categoryId,
categoryName: cat.categoryName,
items: []
}
for (const itm of cat.items) {
const itemId = `${cat.categoryId}-${generateRandomString(5)}`
category.items.push({
item: itm.item,
itemId: itemId,
limit: itm.limit,  
} as Item)
}
tracked.tracked.push(category);

}
// update the tracked list.
db.collection('trackers').doc('eBay').set(tracked, {merge: true})
return true;

您正试图访问;错误的";CCD_ 1。我的意思是:

export const postTracked = async (tracked: Tracked) => {
// set item id's in ingested json.
const newTracked: Tracked = {
tracked: [],
}
for (const cat of tracked.tracked) { // <--- Here you should just use tracked

因为您已经在传递身体对象。正确的代码行应该是

for (const cat of tracked) {

相关内容

  • 没有找到相关文章