【问题标题】:SyntaxError: Cannot use import statement outside a module - Firebase with NodeJSSyntaxError:无法在模块外部使用导入语句 - Firebase 与 NodeJS
【发布时间】:2022-09-28 23:41:16
【问题描述】:

我在 index.js 中的 Node.js 代码

let express = require(\'express\')
const path = require(\'path\');
import { initializeApp } from \'firebase/app\';
import { getDatabase } from \"firebase/database\";
const firebaseConfig = {
    ...
};
const firebaseApp = initializeApp(firebaseConfig);
const database = getDatabase(firebaseApp);

let app = express()
const port = 8080
app.get(\'/updateRelay/:relayId/:status\', function (req, res) {
    const relayId = req.params[\"relayId\"]
    const status = req.params[\"status\"]
    console.log(relayId,status)
    let updateObject = {}
    updateObject[relayId] = status
    database.ref(\"iot-device-001/status\").set(updateObject, function(error) {
        if (error) {
            // The write failed...
            console.log(\"Failed with error: \" + error)
        } else {
            // The write was successful...
            console.log(\"success\")
        }
    })
});

app.get(\'/\', function (req, res) {
    res.sendFile(path.join(__dirname, \'/index.html\'));
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

看在上帝的份上,我无法弄清楚这段代码有什么问题。我已经尝试了所有可用的文档和教程,但最终出现了一些无法解释的错误。它要么是这个,要么是它的模块未找到。 Here 是我遵循的教程的链接,它给了我模块未找到错误

这是我现在遇到的错误

import { initializeApp } from \'firebase/app\';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

标签: node.js firebase-realtime-database


【解决方案1】:

似乎您的函数未定义为模块,因此您不能在其中使用importinside。你必须使用require

您可以通过更换来解决您的问题

import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database" 

经过

var initializeApp = require('firebase/app')
var getDatabase = require('firebase/database')

你会在这里找到更多解释:https://flexiple.com/javascript-require-vs-import/

【讨论】:

  • 现在我得到这个错误,TypeError: initializeApp is not a function
【解决方案2】:

如何从 Node JS 实现它通常有点令人困惑。最简单的方法是按照guide 在 NodeJS 中安装,一旦在本地项目中安装了SDK,就需要initialize it

For that, you should follow the instructions to generate a Private key that you have to add to your project to call the services from it

即便如此,它仍然有点令人困惑,但我找到了一个非常简单的guide,它以可视化和详细的方式解释了如何做到这一点。

【讨论】:

    猜你喜欢
    • 2023-02-08
    • 2021-10-02
    • 2020-03-15
    • 2021-03-16
    • 1970-01-01
    • 2020-08-25
    • 2021-02-21
    • 2021-09-03
    • 2021-07-08
    相关资源
    最近更新 更多