iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
Build on AWS

從零到雲端:AWS 開發之路系列 第 20

Day20 設置前端讓「留言板 」活起來

  • 分享至 

  • xImage
  •  

昨天我們在REST API 做 CRUD(Create / Read / Update / Delete),今天我們在前端設置 HTML 讓它可以直接呼叫 Lambda API,這樣我們就可以在網頁中進行測試啦!

Step1: HTML 結構

首先先在桌面建立資料夾,並使用 nano 建立前端 index.html
HTML 結構
這個頁面主要分成幾個區塊:

1. 新增留言 (POST)

使用者輸入 ID 與 Message
按下「新增」會呼叫 createMessage() 函式

<input type="text" id="postId" placeholder="ID">
<input type="text" id="postMessage" placeholder="Message">
<button onclick="createMessage()">新增</button>

2. 查詢留言 (GET)

使用者輸入 ID
按下「查詢」呼叫 getMessage() 函式

<input type="text" id="getId" placeholder="ID">
<button onclick="getMessage()">查詢</button>

3. 更新留言 (PUT)

使用者輸入要更新的 ID 與新訊息
按下「更新」呼叫 updateMessage()

<input type="text" id="putId" placeholder="ID">
<input type="text" id="putMessage" placeholder="New Message">
<button onclick="updateMessage()">更新</button>

4. 刪除留言 (DELETE)

使用者輸入要刪除的 ID
按下「刪除」呼叫 deleteMessage()

<input type="text" id="deleteId" placeholder="ID">
<button onclick="deleteMessage()">刪除</button>

5. 結果顯示區

所有 CRUD 的回傳結果會顯示在這裡

<div id="output"></div>

Step2: JavaScript 部分

這邊是前端與 Lambda API 互動的核心:

const apiUrl = "你的 Lambda API 網址"; 

抓取輸入並送給 API

1. 新增留言 (POST)

取得輸入欄位的值,並用 fetch 發送 POST 請求給 Lambda
body 將使用者輸入轉成 JSON

const id = document.getElementById('postId').value;
const message = document.getElementById('postMessage').value;

const res = await fetch(apiUrl, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ id, message })
});

2. 查詢留言 (GET)

GET 請求會把 ID 放在 URL 的 query string

const id = document.getElementById('getId').value;
const res = await fetch(`${apiUrl}?id=${id}`, { method: 'GET' });

3. 更新留言 (PUT)

PUT 請求與 POST 類似,把要更新的資料放在 body

const id = document.getElementById('putId').value;
const message = document.getElementById('putMessage').value;

const res = await fetch(apiUrl, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ id, message })
});

4. 刪除留言 (DELETE)

DELETE 請求也用 query string 傳要刪除的 ID

const id = document.getElementById('deleteId').value;
const res = await fetch(`${apiUrl}?id=${id}`, { method: 'DELETE' });

5. 顯示回傳結果

把 Lambda 回傳的 JSON 顯示在頁面 <div id="output">,並使用 JSON.stringify 美化格式

function showOutput(data) {
  document.getElementById('output').textContent = JSON.stringify(data, null, 2);
}

Step3: 更改 Lambda 函數

新增輸入驗證

原本程式碼對 POST 與 PUT 沒有檢查 id 或 message 是否存在,可能會出現不完整資料導致錯誤。這邊確保前端傳入的 JSON 有 id 和 message,如果缺少就會直接回傳錯誤訊息

if (!body.id || !body.message) throw new Error("Missing id or message in body");

新增 OPTIONS 方法

為了解決 CORS 問題,新增了一個 OPTIONS case

  • 功能:
  1. 當瀏覽器做「預檢請求」 (preflight request)時,API 會回應允許的來源、方法與標頭
  2. 避免瀏覽器阻擋 fetch 請求,特別是從本地 HTML 或其他 domain 呼叫 API
case "OPTIONS":
  return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type"
    },
    body: ""
  };

在回傳結果加入 CORS 標頭

  • 功能:
  1. 允許任何來源的瀏覽器呼叫
  2. 支援 GET/POST/PUT/DELETE/OPTIONS
  3. 避免 CORS 相關錯誤
headers: {
  "Content-Type": "application/json",
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type"
}

Step4: 用本地 HTTP server 啟動

打開 終端機 Terminal,進入你的 HTML 檔案所在資料夾
啟動 server:

python3 -m http.server 8000

打開瀏覽器:

http://localhost:8000/index.html

Step5: 成果展示

1. 新增留言 (POST)

https://ithelp.ithome.com.tw/upload/images/20251002/20169251Dz3RIsXd9X.png

2. 查詢留言 (GET)

https://ithelp.ithome.com.tw/upload/images/20251002/20169251XVunO3yZkR.png

3. 更新留言 (PUT)

https://ithelp.ithome.com.tw/upload/images/20251002/20169251Vef7WGbrWN.png
確認更新後的內容已被更新
https://ithelp.ithome.com.tw/upload/images/20251002/20169251oBZmiZPIsz.png

4. 刪除留言 (DELETE)

https://ithelp.ithome.com.tw/upload/images/20251002/20169251SBu7yOkqt4.png


上一篇
Day19 認識 DynamoDB(NoSQL 資料庫)並做簡單 CRUD
下一篇
Day21 本週回顧與心得文章 week3
系列文
從零到雲端:AWS 開發之路22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言