跳到內容

JSONP

JSONP(JSON with Padding)是一種在不支援 CORS 的舊版瀏覽器中進行跨域請求的技術。它透過將 JSON 回應包裝在 JavaScript 函式呼叫中來運作。瀏覽器透過 <script> 標籤載入回應,該標籤不受同源政策限制,包裝函式會以資料作為參數執行。

當你呼叫 c.JSONP() 時,Gin 會檢查 callback 查詢參數。如果存在,回應主體會被包裝為 callbackName({"foo":"bar"})Content-Typeapplication/javascript。如果未提供 callback,回應的行為與標準 c.JSON() 呼叫相同。

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/JSONP", func(c *gin.Context) {
data := map[string]interface{}{
"foo": "bar",
}
// The callback name is read from the query string, e.g.:
// GET /JSONP?callback=x
// Will output : x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}

使用 curl 測試,查看 JSONP 和純 JSON 回應的差異:

Terminal window
# With callback -- returns JavaScript
curl "http://localhost:8080/JSONP?callback=handleData"
# Output: handleData({"foo":"bar"});
# Without callback -- returns plain JSON
curl "http://localhost:8080/JSONP"
# Output: {"foo":"bar"}

另請參閱