好像我正在进行 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;
}
}