Go gin - 从本地浏览器获取数据

Go gin - fetch data from local browser

我有一个用 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")
}

如果我在 Ubuntu 上从 Firefox 控制台(97.0.2(64 位))执行 fetch

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 服务器?

如果您尝试从不同位置发出 ajax 请求,然后请求请求位置然后请求将被 Content Security Policy (CSP) 阻止,这有助于检测和缓解某些类型的攻击。您可以阅读有关 CSP 的更多信息 here.

对于来自该位置的 fetch to work you have to go to the same location and make fetch 请求,您的情况是 http://localhost:8080/

注意:由于您在浏览器中打开位置时定义了到 return json 的根路由,这可能会引发 GET 请求,响应 json 将是 return在浏览器中编辑。