【问题标题】:Using express `app.get()` in firebase cloud functions to access files在 firebase 云函数中使用 express `app.get()` 来访问文件
【发布时间】:2021-08-11 23:28:58
【问题描述】:

我尝试将 Firebase 托管与 Firebase 函数结合使用,这样只有拥有有效 Firebase 令牌的用户才能访问 .html 内容。

当访问 Firebase 托管时,我能够在我的 iOS 应用程序中发送令牌,并且我的云函数被调用并成功解码令牌(我在 Firebase 函数日志中看到“ID 令牌正确解码”)。

之后应该打开 index.html,它位于我的 /functions 文件夹的子文件夹 (/myhomepage) 内(因此不在“/public”内)。

我的 App-Browser 中总是出现错误:“Cannot GET /”

Firebase-Functions-Log 显示:“函数执行耗时 1654 毫秒,完成状态码:404”

index.js 里面的代码:

const admin = require("firebase-admin");
const functions = require('firebase-functions');
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();

admin.initializeApp();

let db = admin.firestore();

// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const validateFirebaseIdToken = async (req, res, next) => {
  functions.logger.log('Check if request is authorized with Firebase ID token');

  if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
      !(req.cookies && req.cookies.__session)) {
    functions.logger.error(
      'No Firebase ID token was passed as a Bearer token in the Authorization header.',
      'Make sure you authorize your request by providing the following HTTP header:',
      'Authorization: Bearer <Firebase ID Token>',
      'or by passing a "__session" cookie.'
    );
    res.status(403).send('Unauthorized');
    return;
  }

  let idToken;
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
    functions.logger.log('Found "Authorization" header');
    // Read the ID Token from the Authorization header.
    idToken = req.headers.authorization.split('Bearer ')[1];
  } else if(req.cookies) {
    functions.logger.log('Found "__session" cookie');
    // Read the ID Token from cookie.
    idToken = req.cookies.__session;
  } else {
    // No cookie
    res.status(403).send('Unauthorized');
    return;
  }

  try {
    const decodedIdToken = await admin.auth().verifyIdToken(idToken);
    functions.logger.log('ID Token correctly decoded', decodedIdToken);
    req.user = decodedIdToken;
    next();
    return;
  } catch (error) {
    functions.logger.error('Error while verifying Firebase ID token:', error);
    res.status(403).send('Unauthorized');
    return;
  }
};

app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/myhomepage', (req, res) => { // <-- The problem seems to be here
    functions.logger.log('Calling get.'); // This line does not get called in my log.
    res.status(200).sendFile('/index.html');
});

exports.myfunction = functions.https.onRequest(app);

令牌成功解码后,如何访问“/functions/myhomepage”内的内容?

【问题讨论】:

    标签: javascript firebase express google-cloud-functions


    【解决方案1】:

    通常您只能以send()redirect()end() 结束HTTP 函数,请参阅doc

    我从未尝试过,但我认为使用sendFile() 不会奏效。如果您想将用户重定向到通过 Firebase 托管提供的静态页面,您应该使用 redirect()。另一种可能性是将 HTML 字符串传递给 send() 方法,请参阅 here

    【讨论】:

    • 感谢您的提示,但我将如何重定向到“/functions/myhomepage/”中的静态文件?它不是通过 Firebase 托管在“公共”目录中的静态文件。
    • 您无法通过托管存储在用于 Cloud Functions 的 functions 目录下的文件来提供服务。您可以将它托管在您的 public 目录下(但它是“公共的”,即任何人都可以访问它),或者您在 Cloud Function 中生成一些 HTML 并通过 send() 将其发回:然后这是一个 @ 987654323@.
    • @Kuhlemann 您是否能够通过在 Firebase 函数中动态生成主页来访问它?如果是这种情况,我会请您发布解决方案作为答案并接受它。这项措施提高了未来用户寻找类似答案的可见度。提前致谢!
    • 遗憾的是,我无法访问位于 functions/ 子文件夹中的可靠静态内容。有时它有效,有时我收到一个 GET 错误。也许函数文件夹不是为主页托管而制作的,但如果我想在分发这些文件之前运行权限检查,我看不到其他地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2019-01-31
    • 2018-03-28
    • 2018-08-06
    • 2020-01-30
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多