我有一個用 Go Gin 撰寫的簡單服務器:
package main
import (
"net/http"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.Default())
router.GET("/", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{"hello": "world"})
})
router.Run(":8080")
}
如果我fetch從 Firefox 控制臺(Ubuntu 上的 97.0.2(64 位))執行:
fetch('http://localhost:8080/')
.then(response => response.json())
.then(data => console.log(data));
我收到以下錯誤:
Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:8080/
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
同時,如果我使用curl從終端執行相同的 HTTP GET 請求,我會得到正確的結果:
curl -X GET http://localhost:8080/
{"hello":"world"}
是否可以使用瀏覽器測驗 Go gin 服務器?
uj5u.com熱心網友回復:
如果您嘗試從不同的位置執行 ajax 請求,然后請求請求位置,則請求將被阻止,Content Security Policy (CSP)這有助于檢測和減輕某些型別的攻擊。您可以在此處閱讀有關 CSP的更多資訊。
要使fetch作業,您必須前往同一位置并從該位置發出fetch請求(在您的情況下)http://localhost:8080/。
注意:由于您已經定義了在瀏覽器中打開位置時回傳 json 的根路徑,這可能會引發 GET 請求,并且回應 json 將在瀏覽器中回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445763.html
標籤:javascript http 走 获取 API 内容安全策略
上一篇:為什么我的腳本正在讀取在我的HTML中鏈接的檔案,這些檔案在GoLang中使用ioutil.ReadFile()讀取時未指定?
