firebase - 使用 BusBoy for firebase 的 FormData 在服务中有效,但在部署中无效
问题描述
情况
我有一个更新用户图像的 firebase 功能。
问题
当我使用 本地运行我的函数时firebase serve
,我使用 Postman 成功地将图像上传到 Firestore。但是,当我运行firebase deploy
并尝试使用 Postman 上传图像时,我收到 500 内部服务器错误。其他功能(不处理 FormData,只处理 json)在我部署它们时工作得很好。
我不明白为什么它在本地工作,但在我做完全相同的事情时却不能在部署时工作。不确定这是否是我缺少的配置中的某些内容,或者我做错了什么。任何帮助,将不胜感激!
代码 users.js
const { admin, db, firebase } = require('../util/admin');
const config = require('../util/config');
exports.postUserImage = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
let imgFileName;
let imgToBeUploaded = {};
const busboy = new BusBoy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Invalid file type
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
return res.status(400).json({ error: 'Invalid file type' });
}
// Extract img extension
const imgDotLength = filename.split('.').length;
const imgExtension = filename.split('.')[imgDotLength - 1];
// Create img file name
imgFileName = `${Math.round(Math.random() * 1000000)}.${imgExtension}`;
// Create img path
const filepath = path.join(os.tmpdir(), imgFileName);
// Create img object to be uploaded
imgToBeUploaded = { filepath, mimetype };
// Use file system to create the file
file.pipe(fs.createWriteStream(filepath));
});
busboy.on('finish', () => {
admin
.storage()
.bucket()
.upload(imgToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imgToBeUploaded.mimetype
}
}
})
.then(() => {
// Create img url to add to our user
const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imgFileName}?alt=media`;
// Add img url to user document
return db.doc(`/users/${req.user.handle}`).update({ imgUrl });
})
.then(() => {
return res.json({ message: 'Image uploaded succesfully' });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error });
});
});
busboy.end(req.rawBody);
};
index.js
const { app, functions } = require('./util/admin');
const FirebaseAuth = require('./util/firebaseAuth');
const {
postUserImage,
} = require('./handlers/users');
app.post('/user/image', FirebaseAuth, postUserImage);
解决方案
推荐阅读
- angular - 通过其实例从另一个组件调用一个组件方法不起作用
- python - 在windows上使用linux cookie时的解密问题
- authorization - 打开策略代理策略管理
- c# - Uri 图像未显示在 android 设备上 (Xamarin)
- c# - Xamarin:从浏览器重定向到本机应用程序不起作用
- python - 根据现有单元格下的值创建一个新列
- wpf - FlowDocument 中的瓦片包装序列
- reactjs - 类型“字符串”不可分配给类型 keyof [Type]
- javascript - 异步等待中的尝试捕获问题
- javascript - 结合多个具有多个属性的 if 语句