【问题标题】:Can't deploy firebase cloud function for flutter无法为 Flutter 部署 Firebase 云功能
【发布时间】:2019-04-25 14:53:11
【问题描述】:

错误:解析函数触发器时出错。

TypeError: require(...) is not a function
    at Object.<anonymous> (A:\Android Projects\buy_storage_try\buy\functions\index.js:21:45)

这是代码行:

const gcs = require('@google-cloud/storage')(gcconfig);

完整的错误信息:

Error: Error occurred while parsing your function triggers.

TypeError: require(...) is not a function
    at Object.<anonymous> (A:\Android Projects\buy_storage_try\buy\functions\index.js:21:45)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at C:\Users\itzpa\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:15:15
    at Object.<anonymous> (C:\Users\itzpa\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:53:3)

代码:

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const Busboy = require('busboy');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fbAdmin = require('firebase-admin');
const uuid = require('uuid/v4');

// // 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!");
// });
const gcconfig = {
  projectId: '***',
  keyFilename: '***.json'
};

const gcs = require('@google-cloud/storage')(gcconfig);

fbAdmin.initializeApp({
  credential: fbAdmin.credential.cert(require('./***.json'))
});

exports.storeImage = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
    if (req.method !== 'POST') {
      return res.status(500).json({ message: 'Not allowed.' });
    }

    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith('Bearer ')
    ) {
      return res.status(401).json({ error: 'Unauthorized.' });
    }

    let idToken;
    idToken = req.headers.authorization.split('Bearer ')[1];

    const busboy = new Busboy({ headers: req.headers });
    let uploadData;
    let oldImagePath;

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      const filePath = path.join(os.tmpdir(), filename);
      uploadData = { filePath: filePath, type: mimetype, name: filename };
      file.pipe(fs.createWriteStream(filePath));
    });

    busboy.on('field', (fieldname, value) => {
      oldImagePath = decodeURIComponent(value);
    });

    busboy.on('finish', () => {
      const bucket = gcs.bucket('flutter-buy.appspot.com');
      const id = uuid();
      let imagePath = 'images/' + id + '-' + uploadData.name;
      if (oldImagePath) {
        imagePath = oldImagePath;
      }

      return fbAdmin
        .auth()
        .verifyIdToken(idToken)
        .then(decodedToken => {
          return bucket.upload(uploadData.filePath, {
            uploadType: 'media',
            destination: imagePath,
            metadata: {
              metadata: {
                contentType: uploadData.type,
                firebaseStorageDownloadTokens: id
              }
            }
          });
        })
        .then(() => {
          return res.status(201).json({
            imageUrl:
              'https://firebasestorage.googleapis.com/v0/b/' +
              bucket.name +
              '/o/' +
              encodeURIComponent(imagePath) +
              '?alt=media&token=' +
              id,
            imagePath: imagePath
          });
        })
        .catch(error => {
          return res.status(401).json({ error: 'Unauthorized!' });
        });
    });
    return busboy.end(req.rawBody);
  });
});

【问题讨论】:

  • 您使用的是哪个版本的 @google/cloud-storage,以及您使用的哪些文档表明您的代码应该是正确的?
  • @google-cloud/storage@2.3.1 我正在使用 Maximilian Schwarzmüller 的视频教程

标签: node.js firebase google-cloud-functions firebase-cli


【解决方案1】:

用这个代替gcconfig。 应该可以正常工作。

const projectId = 'your-project-id';
const keyFilename = 'your-keyfile.json';

const {
    Storage
} = require('@google-cloud/storage');

const gcs = new Storage({
    projectId: projectId,
    keyFilename: keyFilename
});

【讨论】:

    【解决方案2】:

    您使用的 @google-cloud/storage 版本高于或等于 2.0.0。 API 在 2.0.0 中发生了变化。您所遵循的教程已过时,可能是针对 1.x 编写的。

    查看模块的documentation。 SDK的初始化方式是这样的:

    // Imports the Google Cloud client library
    const {Storage} = require('@google-cloud/storage');
    // Creates a client
    const storage = new Storage();
    const bucket = storage.bucket();
    

    【讨论】:

    • 非常感谢。很有帮助。您的解决方案简单易懂
    猜你喜欢
    • 2021-11-17
    • 2018-07-24
    • 2018-08-05
    • 2020-09-04
    • 2021-12-01
    • 2021-01-13
    • 2018-12-29
    • 2021-10-10
    相关资源
    最近更新 更多