iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0

寫一段API呼叫方法

const sendMessageToAPI = async (message: string) => {
  const response = await fetch('https://<id>.execute-api.ap-east-2.amazonaws.com/dev/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ message }),
  })

  if (!response.ok) {
    throw new Error('Failed to send message')
  }

  return response.json()
}

目前前端已經大功告成,但當我們想測試一下前端有無串通API的時候發現….

https://ithelp.ithome.com.tw/upload/images/20251003/20106094d6sWkVe1t4.png
這是一個典型的 CORS (Cross-Origin Resource Sharing) 問題。問題在於 API Gateway 沒有正確配置 CORS 設定,導致瀏覽器阻擋了從 http://localhost:5173 到 API 的請求。

問題分析

  1. Postman 可以正常工作 - 因為 Postman 不受 CORS 政策限制
  2. 瀏覽器被阻擋 - 瀏覽器執行 CORS 安全政策,需要伺服器明確允許跨域請求

在 API Gateway 控制台設定 CORS

勾選及設定以下參數:

https://ithelp.ithome.com.tw/upload/images/20251003/20106094mAWM4Soa6Q.png
我們再來測試一下有無串通,看起來是完全沒問題!!

https://ithelp.ithome.com.tw/upload/images/20251003/20106094kiKgNxJjep.png

重要提醒

  1. 安全考慮 - 生產環境中不要使用 '*',應該指定具體的域名
  2. 重新部署 - 修改設定後務必重新部署 API
  3. 測試 - 可以用瀏覽器開發者工具查看 Network 標籤,確認回應是否包含正確的 CORS 標頭

建議先使用方法一在 API Gateway 控制台設定,這是最簡單的方式。


上一篇
Day 18 前端升級:打造 AI 問答介面
下一篇
Day 20 打通任督二脈:完整流程串接測試
系列文
來都來了,那就做一個AWS從0到100的微服務AI小平台!22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言