AI AI Club
← 返回文章列表

Gemini API 前端 CORS 问题:以服务端整合保护金钥

在 Vue/React 中直调接口报跨域错误?深度科普浏览器同源策略与 API Key 防盗刷原理,指导搭建极简轻量后端中转层。

一、为什么谷歌官方接口直接禁止前端跨域

如果在前端代码中写 fetch('https://generativelanguage.googleapis.com...'),浏览器控制台会立刻弹出红色的 CORS 错误。
这是谷歌刻意设计的安全防御机制!
如果在前端浏览器直接调用,任何访问你网页的用户按下 F12 就能直接窃取你的 API Key 去大肆盗刷。

二、标准后端中转(Proxy Pattern)架构

用户浏览器 -> 你的自有后端接口(如 /api/chat) -> 谷歌官方 API。
所有环境变量保存在后端安全的服务器内存中,对外部世界彻底隐身。

三、Next.js API Route 极简实现

// app/api/chat/route.ts
import { GoogleGenerativeAI } from "@google/generative-ai";
import { NextResponse } from "next/server";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

export async function POST(req: Request) {
const { prompt } = await req.json();
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent(prompt);
return NextResponse.json({ reply: result.response.text() });
}

密钥配置规范见:[Gemini API 密钥管理总指南](https://aihuiyuan.club/articles/gemini-api-key-google-ai-studio-free)。

联系我们

会员开通、订单问题或合作咨询,欢迎联系。

QQ1192214187
邮箱winky20000401@gmail.com