簡體   English   中英

使用 javascript 將 firebase 雲 function 中的數組發送到實時數據庫

[英]Send an array in firebase cloud function to the realtime database using javascript

我正在研究雲函數來創建一個 API ,它采用這樣的數組字典

["keyOne":
     ["itemOne","itemTwo"],
  "keyTwo":
     ["itemone","itemTwo"]
] 

我創建了雲 function 將其放入體內,我使用 postman 發送了正文,但我仍然在 firebase 日志中作為字符串存儲字典時遇到問題

雲 function 代碼:

exports.createProduct = functions.https.onRequest((req, res) => {
    if (req.method !== 'POST') {
        return res.status(500).json({
            message: 'not allowed'
        })
    }
    console.log(req.body.variants)
    var firebaseRef = db.ref("product").push();
    firebaseRef.set({
        variants: req.body.variants
    });
    res.status(200).json({
        message: req.body
    });
});

我發送的變體:

variants:["Key":["items1","items2","items3"]]

像這樣存儲在 firebase 日志中:

variants: "[\"Key\":[\"items1\",\"items2\",\"items3\"]]"

在最后一個屏幕截圖中,您似乎正在發送一個字符串,這就是 Firebase 存儲的內容。

如果需要,您可以從 Cloud Functions 代碼中的字符串解析數組:

firebaseRef.set({
  variants: JSON.parse(req.body.variants);
})

您的 JSON 中似乎也有語法錯誤:

"[\"Key\":[\"items1\",\"items2\",\"items3\"]]"

我能做到的最接近的是:

"[{\"Key\":[\"items1\",\"items2\",\"items3\"]}]"

或者

"{\"Key\":[\"items1\",\"items2\",\"items3\"]}"

我還強烈建議在字符串周圍使用單引號,這樣您就不必轉義其中的雙引號:

'[{"Key":["items1","items2","items3"]}]'

我建議不要通過字符串連接創建 JSON,而是使用JSON.stringify()來防止生成無效的 JSON。

JSON.stringify([{Key: ["items1", "items2", "items3"]}])

這使:

"[{"Key":["items1","items2","items3"]}]"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM