firebase init, чтобы инициализировать Firebase Configurable. Затем выберите Functions и Emulators.5001, а для пользовательского интерфейса назначьте порт как 2000.functions/index.ts:import * as functions from "firebase-functions";
export const helloWorld = functions.https.onCall((data, context) => {
console.info(data);
return { success : true };
});
npm run build внутри папки functions/, чтобы создать функцию. Затем запустите эмулятор firebase с помощью firebase emulators: startimport { initializeApp } from "firebase/app";
import { connectFunctionsEmulator, getFunctions, httpsCallable } from "firebase/functions";
const firebaseConfig = { /*...firebaseConfig*/ };
const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);
const useEmulator:boolean = true
if (useEmulator) {
connectFunctionsEmulator(functions, "localhost", 5001);
}
const triggerCallable = httpsCallable(functions, "helloWorld");
const result = await triggerCallable({
message : "Hello world",
count: 1
});
console.info(result); // expected : { success : true }
index.ts с помощью npm run build && node dist/index.js, вы получите:node:internal/process/esm_loader:97
internalBinding('errors').triggerUncaughtException(
^
[FirebaseError: internal] {
code: 'functions/internal',
customData: undefined,
details: undefined
}
Я даже не получаю сообщение об инициализации функции в журналах эмулятора. Хотя я понимаю
✔ functions: Loaded functions definitions from source: helloWorld.
Похоже, функция даже не инициализирует ее правильно. Я также пробовал onCall() функции Firebase 2-го поколения, и результат тот же FirebaseError: internal
firebase.json:
{
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run build"
]
}
],
"emulators": {
"functions": {
"port": 5001
},
"ui": {
"enabled": true,
"port": 2000
},
"singleProjectMode": true
}
}
Структура проекта:
.
├── database-debug.log
├── dist
│ ├── index.js
│ └── index.js.map
├── firebase-debug.log
├── firebase.json
├── functions
│ ├── lib
│ │ ├── index.js
│ │ └── index.js.map
│ ├── package.json
│ ├── package-lock.json
│ ├── src
│ │ └── index.ts
│ └── tsconfig.json
├── package.json
├── package-lock.json
├── pubsub-debug.log
├── src
│ └── index.ts
├── tsconfig.json
└── ui-debug.log
Где мой tsconfig.json клиентского приложения:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"sourceMap": true,
"outDir": "dist"
},
"include": ["src/**/*"],
}
Я все перепробовал, помогите кто-нибудь :) Заранее спасибо.
@RenaudTarnec Да, я видел это. Я тоже пробовал с этим, но тот же результат.
Я не могу повторить, используя предоставленный вами код (я получаю { data: { success: true } }, как и ожидалось). Можете ли вы поделиться журналами эмулятора функций, чтобы убедиться, что он запускается правильно? Должно быть не менее 2 строк: functions Loaded functions definitions from source: helloWorld. и functions http function initialized (http://127.0.0.1:5001/<project-id>/us-central1/helloWorld).
@Kiana Мой эмулятор печатает ✔ functions: Loaded functions definitions from source: helloWorld. и ✔ functions[us-central1-helloWorld]: http function initialized (http://127.0.0.1:5001/<project-id>/us-central1/helloWorld).
@Kiana и наряду с ними я также получаю предупреждение вроде ⚠ functions: Your requested "node" version "16" doesn't match your global version "18". Using node@18 from host.

Я думаю, что проблема может быть связана с https://github.com/nodejs/node/issues/40537. TLDR; начиная с Node 17 произошли изменения в разрешении IP по умолчанию. По умолчанию теперь используется петлевой адрес IPv6, то есть ::1.
Поскольку похоже, что эмулятор использует хост 127.0.0.1, для решения этой проблемы попробуйте изменить localhost на 127.0.0.1.
if (useEmulator) {
connectFunctionsEmulator(functions, "127.0.0.1", 5001);
}
Вы видели этот раздел документации о «Инструментировании вашего приложения для вызываемых функций»?