首页 > 解决方案 > Unable to post to json data

问题描述

I'm getting this error while trying to post image together with json data. Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "price")enter image description here

   let imageUrl;

   const BusBoy = require('busboy');
   const path = require('path');
   const os = require('os');
   const fs = require('fs');

   const busboy = new BusBoy({ headers: req.headers });

   let imageToBeUploaded = {};
   let imageFileName;

   busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
     console.log(fieldname, file, filename, encoding, mimetype);
     if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
       return res.status(400).json({ error: 'Wrong file type submitted' });
     }
     // my.image.png => ['my', 'image', 'png']
     const imageExtension = filename.split('.')[filename.split('.').length - 1];
     // 32756238461724837.png
     imageFileName = `${Math.round(
       Math.random() * 1000000000000
     ).toString()}.${imageExtension}`;
     const filepath = path.join(os.tmpdir(), imageFileName);
     imageToBeUploaded = { filepath, mimetype };
     file.pipe(fs.createWriteStream(filepath));
   });
   busboy.on('finish', () => {
     admin
       .storage()
       .bucket(`${config.storageBucket}`)
       .upload(imageToBeUploaded.filepath, {
         resumable: false,
         metadata: {
           metadata: {
             contentType: imageToBeUploaded.mimetype
           }
         }
       })
       .then(() => {
         imageUrl = `https://firebasestorage.googleapis.com/v0/b/${
           config.storageBucket
         }/o/${imageFileName}?alt=media`;
         const newProduct = {
             description: req.body.description,
             price: req.body.price,
             title: req.body.title,
             createdAt: new Date().toISOString(),
             likeCount:0,
             reviewCount:0,
             orderCount: 0,
             storeName: req.user.userName,
             sellerImage: req.user.imageUrl,
             imageUrl: imageUrl,
         };

         db .collection('products')
             .add(newProduct)
             .then(doc => {
                 const resProduct = newProduct;
                 resProduct.productId = doc.id;
                 res.json(resProduct);
             })

       })
       .then(() => {
         return res.json({ message: 'product uploaded successfully' });
       })
       .catch((err) => {
         console.error(err);
         return res.status(500).json({ error: 'something went wrong' });
       });
   });
   busboy.end(req.rawBody);
};

Is it possible to post file and json data together in postman?

标签: node.jsfirebasefirebase-realtime-databasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


错误消息告诉您,您有一个名为“price”的字段,其值未定义。Undefined 不是有效的 Firestore 值。你必须弄清楚为什么会这样以及它应该是什么。检查 的值req.body.price。如果你不能给它一个合适的值,把它从对象中删除。


推荐阅读