[golang]Golang 設定 CORS 規則
Golang 設定 CORS 規則 (AllowOrigins)
在 Golang 的 gin 框架中,你可以使用 github.com/gin-contrib/cors 來設定 CORS(跨來源資源共享)。
AllowOrigins 設定
AllowOrigins設定的是允許請求的來源網址- 當你使用 Postman 測試時,應該設定為
"*"或["http://localhost"]
CORS 設定範例
AllowOrigins 設定解析
| 設定值 | 適用情境 | 說明 |
|---|---|---|
AllowOrigins: []string{"*"} | 適用於 Postman 或測試環境 | 允許任何網域發送請求 |
AllowOrigins: []string{"http://localhost"} | 適用於本機開發 | 只允許 http://localhost 的請求 |
AllowOrigins: []string{"http://example.com"} | 限制為特定網域 | 只允許 example.com 來源的請求 |
Postman 測試
- 開啟 Postman
- 設定請求
- 方法:
GET - 網址:
http://localhost:8080/
- 方法:
- 送出請求
- 確認回應:json複製編輯{ "message": "CORS 設定成功!" }
結論
- Postman 不會受到 CORS 限制,但如果你用瀏覽器發 AJAX 請求,則需要正確設定
AllowOrigins。 - 開發環境 (
localhost):設定AllowOrigins: []string{"http://localhost"}。 - 允許所有來源(測試用):設定
AllowOrigins: []string{"*"}。
留言
張貼留言