這套架構是專為學生、獨立開發者與教學實戰設計的「完全免費、零維運主機、金鑰永久安全隔離」的現代 AI 全端解決方案。前端部署於 GitHub Pages,後端利用 Google Apps Script (GAS) 充當安全中繼代理,對接 OpenRouter 大模型並在 Google Sheet 寫入即時對話審計日誌。
在全端開發中,學生最常犯的重大資安事故,就是把 OpenAI 或 OpenRouter 的 API Key 直接寫進前端 HTML / JS,然後推上公開的 GitHub 倉庫,幾分鐘內就會被自動爬蟲盜刷掏空。
當前端網頁 (drchunchihchen.github.io) 嘗試呼叫外部 API 時,瀏覽器會嚴格執行同源政策 (CORS)。此外,Google Apps Script 執行時會將請求從 script.google.com 經由 HTTP 302 重導向至 script.googleusercontent.com。
redirect: "follow" 與 mode: "cors",否則請求會在重導向階段被瀏覽器強制中斷。ContentService.createTextOutput() 並設置 MimeType 為 JSON,才能讓瀏覽器安心接收數據。傳統架設後端需要租用 AWS EC2、GCP VM 或 Heroku,每月需支付 150~800 元台幣,還得自己設定 Nginx 反向代理、SSL 憑證定時更新與 Linux 防火牆。
不需要再花時間安裝 MySQL 或設定 MongoDB,直接將 Google 試算表當成雲端持久化資料庫使用!
SpreadsheetApp.openById().appendRow([...]),以超低延遲自動寫入新列。這種「前端靜態純展示 + 輕量無伺服器做 BFF (Backend For Frontend) + 外部大模型 API」的模式,是目前敏捷開發 AI 應用最精煉的實戰架構。學生學會這套模式後,無論是寫個人履歷網站、期末專題、商業數據儀表板,都能在「0 元成本」的前提下隨插即用!
這是放在 GitHub Pages 靜態網站中(例如 digital_jitong.js)用來向 Google Apps Script 發送請求的精簡程式碼:
// 1. 設定你的 Google Apps Script 部署網址 (Web App URL)
const GAS_BACKEND_URL = "https://script.google.com/macros/s/AKfycbyZJTyyxiK5C_ow8KPRhtCRlxZQOV3sg3vrZPVtTWp6xtjsypbRdm7a_zTgrV3jJAUk/exec";
/**
* 向 GAS 後端發送對話與截圖資訊
* @param {string} promptText 學生提問文字
* @param {string|null} base64Image 多模態截圖 (可選,Base64 字串)
* @param {string} pageContext 當前頁面圖表與篩選條件上下文
*/
async function askDigitalJitong(promptText, base64Image = null, pageContext = "") {
const payload = {
message: promptText,
context: pageContext,
imageBase64: base64Image || null,
timestamp: new Date().toISOString()
};
try {
// 關鍵設定:method 為 POST,mode 為 cors,redirect 必須為 follow!
const response = await fetch(GAS_BACKEND_URL, {
method: "POST",
mode: "cors",
cache: "no-cache",
redirect: "follow", // 重要!GAS 執行時會 302 重導向到 script.googleusercontent.com
headers: {
"Content-Type": "text/plain;charset=utf-8" // 避免觸發複雜預檢 (preflight)
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`伺服器回應異常,狀態碼: ${response.status}`);
}
const data = await response.json();
console.log("【數位乩童開示回傳】:", data.reply);
return data.reply;
} catch (error) {
console.error("【連線失敗】:", error);
throw error;
}
}
redirect: "follow":這是與 GAS 通訊最關鍵的一行。Google 在執行 Apps Script 時,會先回傳 HTTP 302 狀態碼,告訴瀏覽器真正的執行容器在 googleusercontent.com。如果沒有設定 follow,瀏覽器會直接中斷並拋出 CORS 錯誤。headers: {"Content-Type": "text/plain"}:在簡單 POST 請求中使用純文字或標準 JSON 封裝,能大幅降低瀏覽器觸發 OPTIONS 預檢失敗的機率。
這是部署在 Google Apps Script 中的 Code.gs 核心程式碼:
/**
* 處理前端 POST 請求 (BFF 安全中繼)
*/
function doPost(e) {
try {
// 1. 安全取得儲存在專案屬性中的 API Key (前端完全看不到!)
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty("OPENROUTER_API_KEY");
const sheetId = props.getProperty("LOG_SHEET_ID"); // 儲存日誌的 Google Sheet ID
if (!apiKey) {
return jsonResponse({ error: "尚未設定 OPENROUTER_API_KEY 金鑰" }, 500);
}
// 2. 解析前端傳來的 JSON 數據
const contents = e.postData.contents;
const requestData = JSON.parse(contents);
const userMessage = requestData.message || "";
const pageContext = requestData.context || "";
const imageBase64 = requestData.imageBase64 || null;
// 3. 組裝發往 OpenRouter 的 Prompt 與多模態 Payload
const messages = [
{
role: "system",
content: "你是「數位乩童」,說話靈光四溢、帶有玄學幽默但技術極度扎實的 AI 導師。你的真身是香港中文大學資訊工程系博士陳純質。"
}
];
// 多模態訊息組裝
const userContent = [];
userContent.push({
type: "text",
text: (pageContext ? `【學員當前操作畫面上下文】\n${pageContext}\n\n` : "") + userMessage
});
if (imageBase64) {
userContent.push({
type: "image_url",
image_url: {
url: imageBase64.startsWith("data:") ? imageBase64 : `data:image/png;base64,${imageBase64}`
}
});
}
messages.push({ role: "user", content: userContent });
// 4. 呼叫 OpenRouter API 進行 Claude Haiku 推論
const openRouterUrl = "https://openrouter.ai/api/v1/chat/completions";
const payload = {
model: "anthropic/claude-3.5-haiku",
messages: messages,
temperature: 0.7
};
const options = {
method: "post",
contentType: "application/json",
headers: {
"Authorization": "Bearer " + apiKey,
"HTTP-Referer": "https://github.com/drchunchihchen/dataviz",
"X-Title": "Digital Jitong Course Assistant"
},
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(openRouterUrl, options);
const resJson = JSON.parse(response.getContentText());
const replyText = resJson.choices[0].message.content;
// 5. 異步記錄到 Google Sheets 試算表
if (sheetId) {
try {
const sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
sheet.appendRow([
new Date(),
userMessage,
replyText.substring(0, 500),
imageBase64 ? "有截圖" : "無截圖",
"claude-3.5-haiku"
]);
} catch (sheetErr) {
Logger.log("日誌記錄失敗: " + sheetErr.message);
}
}
// 6. 回傳標準 JSON 格式給前端
return jsonResponse({
status: "success",
reply: replyText
});
} catch (err) {
return jsonResponse({ error: err.message }, 500);
}
}
/**
* 輔助函式:建立符合 CORS 規範的 JSON 輸出
*/
function jsonResponse(data, statusCode = 200) {
const output = ContentService.createTextOutput(JSON.stringify(data));
output.setMimeType(ContentService.MimeType.JSON);
return output;
}
/**
* 支援健康檢查 GET 請求
*/
function doGet(e) {
return jsonResponse({
status: "online",
service: "數位乩童 GAS Backend Gateway",
time: new Date()
});
}
PropertiesService.getScriptProperties():將敏感密鑰隔離在雲端環境變數中,即便專案程式碼截圖展示給學生看,金鑰也絕不會外洩。ContentService.createTextOutput().setMimeType(ContentService.MimeType.JSON):GAS 專屬的輸出方式,能正確附帶 JSON MIME 標頭。SpreadsheetApp.appendRow():自動在試算表尾端新增一行,免寫 SQL,天然具備時間戳與資料庫審計功能。
點選左側齒輪「專案設定」,拉至下方「指令碼屬性」,點擊「新增指令碼屬性」,屬性名稱填 OPENROUTER_API_KEY,值貼上你的 OpenRouter 憑證,儲存完成隔離。
點擊右上角「部署」→「新增部署作業」→ 選擇齒輪「網路應用程式」:
• 執行身分:我 (你的 Google 帳號)
• 誰可以存取:任何人 (Anyone)(重要!)
取得 https://script.google.com/macros/s/.../exec 網址即可!
Code.gs 程式碼後,必須點擊「部署」→「管理部署作業」→ 點擊鉛筆圖示編輯 → 選擇「新版本」再點儲存!如果沒有切換成新版本,外面的 Web 網址依舊會執行舊程式碼。