網站搜尋

javascript - 取得存取權杖時發生錯誤:發送請求時出錯:getaddrinfo ENOTFOUND metadata.google.internal。有時會發生錯誤嗎?


作為前言,這是錯誤。

Promise { <pending> }
nodejsproject\node_modules\firebase-admin\lib\utils\error.js:44
        var _this = _super.call(this, errorInfo.message) || this;
                           ^
FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".
    
  errorInfo: {
    code: 'app/invalid-credential',
    message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".'
  },
  codePrefix: 'app'
}

據我了解,這個錯誤是因為我的參數無效或其他某些原因導致 Firebase 初始化不正確。

現在我正在這樣初始化應用程式:initializeApp();。

所以初始化是有效的。當我運行一個命令例如 const userInfo=await getAuth().verifyIdToken(authorization); 時,該命令可以運行並且我可以獲得 userInfo,但當我運行一個命令例如 const userInfo=await getAuth().getUser(uuid); 時,它就會失敗。

據我所知,語法是正確的,我使用這些方法的方式也正確。我只是對於為什麼在使用一個方法時會出現 initializeApp 錯誤,而使用另一個方法時卻不會感到不確定。

答案#1

我弄清楚了如何讓兩個功能在不出錯的情況下運作。為了解決我的問題,我更改了環境變數。

之前,我有:

GCLOUD_PROJECT="project-name"
FIREBASE_CONFIG={keyDetailsHere}

之後,我將其更改為值為服務帳戶密鑰路徑的位置:

GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

我不確定為什麼原本的程式在某些函式(特別是 getAuth().verifyIdToken())上能運作,但在其他函式上卻失敗。據我理解,如果 initializeApp() 留空,它會檢查環境變數 GOOGLE_APPLICATION_CREDENTIALS。如果找到,它會使用你明確設定的憑證;如果沒有,它會使用 Google 的應用程式默認憑證。在使用 Google 應用程式默認憑證設置完成後,它會查看 FIREBASE_CONFIG 環境變數以取得初始化選項。

文檔摘錄:「由於在 Google 環境中默認憑證查找是完全自動化的,無需提供環境變數或其他配置,因此這種初始化 SDK 的方式強烈建議用於在 Compute Engine、Kubernetes Engine、App Engine 和 Cloud Functions 上運行的應用程序。」

我的理解是,我原本的設定無法運作,因為我是在本地開發,而不是在 Google 環境中,所以無法獲取適當的 Google 應用程式預設憑證。

供參考,這裡是文件:LINK

答案#2

在此錯誤中,原因是 JSON 憑證未正確實作或導入

Firebase 的 json 無法匯入或 applicationDefault() 的 token 已過期,所以現在你匯入你的 fcm json 檔案。

跟隨這個步驟 ->

import json from "your-jsonfile-028f728f9457.json" assert { type: "json" };

或

import fs from "fs";

let jsonData = JSON.parse(
  fs.readFileSync("./your-jsonfile-028f728f9457.json", "utf-8")
);

在這個 jsonData 中使用你的憑證

admin.initializeApp({
  credential: admin.credential.cert(jsonData),
  projectId: "fcm=project-id",
});