使用Go Gin从本地浏览器获取数据

huangapple go评论79阅读模式
英文:

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")
}

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

fetch('http://localhost:8080/')
  .then(response => response.json())
  .then(data => console.log(data));

我会得到以下错误:

内容安全策略:页面的设置阻止了加载 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服务器?

英文:

I have a simple server written with 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")
}

If I do a fetch from Firefox console (97.0.2 (64-bit) on Ubuntu):

fetch('http://localhost:8080/')
  .then(response => response.json())
  .then(data => console.log(data));

I get the following error:

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.

While, if I do the same HTTP GET request from a terminal with curl, I get the correct result:

curl -X GET http://localhost:8080/

{"hello":"world"}

Is it possible to test the Go gin server using the browser?

答案1

得分: 1

如果您尝试从不同的位置进行ajax请求,那么请求将被"内容安全策略(CSP)"阻止,该策略有助于检测和缓解某些类型的攻击。您可以在这里了解更多关于CSP的信息。

要使fetch正常工作,您需要在相同的位置上进行fetch请求,在您的情况下是http://localhost:8080/

注意:由于您已经定义了根路由以返回json,当您在浏览器中打开该位置时,可能会发起一个GET请求,并且响应的json将在浏览器中返回。

英文:

If you try to do ajax request from different location then the request request location then the request will be blocked by Content Security Policy (CSP) which help to detect and mitigate certain types of attacks. You can read more about CSP here.

For fetch to work you have to go to the same location and make fetch request from that location in your case it is http://localhost:8080/.

Note: Since you have defined the root route to return json when you open the location in browser which may raise a GET request and the response json will be returned in browser.

huangapple
  • 本文由 发表于 2022年3月18日 01:52:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/71516936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定