node.js - 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?
解决方案
错误消息告诉您,您有一个名为“price”的字段,其值未定义。Undefined 不是有效的 Firestore 值。你必须弄清楚为什么会这样以及它应该是什么。检查 的值req.body.price
。如果你不能给它一个合适的值,把它从对象中删除。
推荐阅读
- r - R - 如何使用循环和子集计算 MICE 的平均值?
- python - 使用 Python 将 WEBM 文件转换为 WAV 文件
- jenkins - 如何在 Jenkins 中捕获合并请求冲突并通知 GitLab
- javascript - 更新多个 useState 时的执行顺序
- javascript - 如何在javascript中将对象添加到特定的索引数组?
- android - 概述 TextInputLayout 中带有提示的错误
- python-3.x - 从具有移位索引的现有列表创建新列表
- c++ - 打印换行符时 C++ 中的意外输出
- python - 使用自制的“深拷贝”撤消功能?
- dependencies - 在 npm install 期间防止 ua-parser-js 安装