我正在尝试使用firebase storgae在react中实现图像上传,但遇到错误“在cmd中运行firebase deploy时,“解析您的函数触发firebase时发生错误”。我似乎无法弄清楚错误的来源。 该错误可以在代码底部看到。
const functions = require("firebase-functions");
const cors = require("cors")({origin: true});
const Busboy = require("busboy");
const fs = require("fs");
const gcconfig = {
projectId: "abcdefgh-13ff0",
keyFilename: "abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json"
}
const gcs = require("@google-cloud/storage")(gcconfig);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method !== "POST"){
return res.status(500).json({
message: "Not Allowed"
});
}
const busboy = new Busboy({headers: req.headers});
let uploadData = null;
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
const filepath = path.join(os.tmpdir(), filename);
uploadData = {file: filepath, type: mimetype};
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
const bucket = gcs.bucket("gs://abcdefgh-13ff0.appspot.com");
bucket.upload(uploadData.file, {
uploadType: "media",
metadata: {
metadata: {
contentType: uploadData.type
}
}
})
.then(() => {
return res.status(200).json({
message: "It worked"
});
})
.catch(err => {
return res.status(500).json({
error: err
});
});
return;
});
busboy.end(req.rawBody);
return null;
});
});
这是错误
Error: Error occurred while parsing your function triggers.
C:\Users\Joseph\node_modules\streamsearch\lib\sbmh.js:1
(function (exports, require, module, __filename, __dirname) {
SyntaxError: Invalid or unexpected token
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
答案 0 :(得分:0)
您遇到的错误可能是2件事中的1件事,但可能两者同时存在...
keyFileName
文件(abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json)应该位于您的src文件夹中,以便可以直接访问它。
您应编辑以下代码行:
const gcconfig = {
projectId: "abcdefgh-13ff0",
keyFilename: "abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json"
}
const gcs = require("@google-cloud/storage")(gcconfig);
要读:
const gcs = require('@google-cloud/storage')
gcs.projectId ='abcdefgh-13ff0'
gcs.keyFilename = 'abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json'
//就我而言,这应该可以解决您遇到的问题!