为什么 firebase 云函数返回 404 未找到以及如何修复?

问题描述 投票:0回答:1

好像我正在进行 API 调用,但我收到了 404。我看到云控制台函数调用计数器中添加了函数调用。但我看不到日志

console.log("function call begin");
我做错了什么?


import * as express from "express";
import * as cors from "cors";
const app = express();

app.use(cors({origin: true}));
const corsHandler = cors({origin: true});
app.use(corsHandler);

const API_KEY = "***";
const genAI = new GoogleGenerativeAI(API_KEY);

app.get("/api", async (req, res) => {
  console.log("function call begin");
  const prompt = req.query.prompt as string;

  if (!prompt) {
    res.status(400).send("Prompt query parameter is required");
    return;
  }
  console.log("Will try to generate text:", prompt);
  try {
    const model = genAI.getGenerativeModel({model: "gemini-1.5-flash"});
    const result = await model.generateContent(prompt);
    const response = await result.response;
    const text = await response.text();
    console.log("Generated text:", text);
    res.status(200).send(text);
  } catch (error) {
    console.error(error);
    res.status(500).send("Error generating content");
  }
});

export const api = functions.https.onRequest(app);

然后在flutter中调用它

final FirebaseFunctions functions = FirebaseFunctions.instance;

  Future<String?> getResponse(String prompt) async {
    try {
      final HttpsCallable callable = functions.httpsCallable('api');
      final response = await callable.call(<String, dynamic>{
        'prompt': prompt,
      });

      return response.data as String?;
    } catch (e) {
      print('Error: $e');
      return null;
    }
  }

我尝试直接拨打电话,但结果相同

Future<String?> getResponse(String prompt) async {
    try {
      // Construct the request body
      final Map<String, String> body = {
        'prompt': prompt,
      };

      // Make the POST request
      final response = await http.post(
        Uri.parse(functionUrl),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(body),
      );

      // Check for successful response
      if (response.statusCode == 200) {
        // Return the response body as a string
        return response.body;
      } else {
        print('Error: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error: $e');
      return null;
    }
  }
flutter firebase google-cloud-functions
1个回答
0
投票

您实际上无法使用 Firebase 可调用 SDK 来调用不是使用

onCall
(而不是
onRequest
)定义的可调用函数的端点,如文档中所示。 可调用函数有自己的协议,您在这里没有使用它。 相反,您应该完全忽略 Firebase 客户端库,而只使用其他一些 HTTP 客户端库来调用 Express 应用程序的函数端点。

© www.soinside.com 2019 - 2024. All rights reserved.