寫一段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的時候發現….
這是一個典型的 CORS (Cross-Origin Resource Sharing) 問題。問題在於 API Gateway 沒有正確配置 CORS 設定,導致瀏覽器阻擋了從 http://localhost:5173
到 API 的請求。
勾選及設定以下參數:
我們再來測試一下有無串通,看起來是完全沒問題!!
'*'
,應該指定具體的域名建議先使用方法一在 API Gateway 控制台設定,這是最簡單的方式。