【问题标题】:Firebase Cloud Functions - "not defined" error for npm dependency & including a module with client side codeFirebase Cloud Functions - npm 依赖的“未定义”错误 & 包括带有客户端代码的模块
【发布时间】:2018-02-27 16:10:20
【问题描述】:

我正在使用 Firebase 开发一个应用,并且我正在使用 Cloud Functions 来生成二维码等。

我有两个问题

1,我正在尝试在 Cloud Functions 中使用 qrcodejs npm 包。
我在functions 目录中运行了sudo npm install --save qrcodejs

这是functions目录下package.js文件的相关部分:

"dependencies": {
    "firebase-admin": "~5.8.1",
    "firebase-functions": "^0.8.1",
    "kjua": "^0.1.2",
    "qrcodejs": "^1.0.0"
  },

部署并运行代码时,我在 Cloud Functions 日志 中收到 'QRCode is not defined' 错误。

这是我的 functions/index.js 文件:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var qrcodejs = require('qrcodejs')

exports.events = functions.https.onRequest((req, res) => {

  const eventID = req.path
  const promise = admin.database()
  .ref('events' + eventID)
  .once('value')

  return promise.then(result => {

    var qrcode = new QRCode("test", {
      text: "http://jindo.dev.naver.com/collie",
      width: 128,
      height: 128,
      colorDark : "#000000",
      colorLight : "#ffffff",
      correctLevel : QRCode.CorrectLevel.H
    });

    var html = `
    <!doctype html>
      <head>
        <title>${result.val().title}</title>
      </head>
      <body>
        ${qrcode}</br>
        ${result.val().title}
      </body>
    </html>`

    return res.status(200).send(html);
  });
});

错误指向这一行: var qrcode = new QRCode("test", {。 我很确定我在 html 字符串中的插入也是错误的,但是错误指向上面的行。

2,我也尝试过使用另一个二维码 npm 包,kjua。我更喜欢使用 kjua,但我还有一个问题。

在运行 firebase deploy 时,我在“i functions: preparing functions directory for uploading...”步骤中收到以下错误:

ReferenceError: window is not defined

它指向functions/node_modules/kjua/dist/kjua.min.js文件的第二行。

问题似乎在于代码是在浏览器中运行时编写的。我还能以某种方式将此包作为依赖项包含在 Cloud Functions 中吗?

非常感谢

【问题讨论】:

  • 那个 qrcodejs 库说它适用于浏览器,而不是 node.js。也许这就是问题所在。 “IE6~10、Chrome、Firefox、Safari、Opera、Mobile Safari、Android、Windows Mobile、ETC。”​​
  • @DougStevenson 看来你是对的!我找到了一个 node.js 的二维码生成器包,它正在工作! github.com/soldair/node-qrcode 非常感谢!我是 JS 新手,还不明白 node.js 是什么。

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


【解决方案1】:

为了回答,对于像我这样的人,你只需要替换

windowglobal 可以在 node.js / 云函数中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2020-02-01
    • 2018-03-15
    • 2018-06-11
    • 2013-08-08
    • 2021-12-15
    相关资源
    最近更新 更多