CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

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

Cors React and Gin-Gonic Gin

问题

我在开发环境中遇到了一个问题,实现了React前端和Go语言Gin-Gonic框架之间的跨域资源共享。下面是浏览器控制台的日志:

CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

React应用程序发送POST请求的控制台日志:

这是Go框架接收到的请求,可以看到预检请求未经验证

我尝试了两种方法,一种是验证预检请求并在React的OPTIONS请求中返回200,如下所示:

  1. func preflight(c *gin.Context) {
  2. c.Header("Access-Control-Allow-Origin", "*")
  3. c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
  4. c.JSON(http.StatusOK, struct{}{})
  5. }

这种方法没有帮助,另外,我在访问控制允许的来源中包含了一个通配符域名的中间件,以及http://localhost:3000,如下所示:

  1. func CORSMiddleware() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. c.Header("Access-Control-Allow-Origin", "*")
  4. c.Header("Access-Control-Allow-Credentials", "true")
  5. c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
  6. c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")
  7. if c.Request.Method == "OPTIONS" {
  8. c.AbortWithStatus(204)
  9. return
  10. }
  11. c.Next()
  12. }
  13. }

我还尝试了gin cors包,如此处所示:github.com/gin-contrib/cors,但请求仍然被阻止。

CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

这些是我的路由的一部分:

  1. r := gin.Default()
  2. //r := gin.New()
  3. config := cors.DefaultConfig()
  4. config.AllowOrigins = []string{"*"}
  5. // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
  6. // config.AllowAllOrigins = true
  7. r.Use(cors.New(config))
  8. //system routes
  9. router.NotFound(r)
  10. router.NoMethods(r)
  11. //static routes
  12. router.ServeStatic(r)

这是我的路由方法:

  1. func NotFound(route *gin.Engine) {
  2. route.NoRoute(func(c *gin.Context) {
  3. c.JSON(404, gin.H{"msg": "Not Found"})
  4. })
  5. }
  6. func NoMethods(route *gin.Engine) {
  7. route.NoMethod(func(c *gin.Context) {
  8. c.JSON(405, gin.H{"msg": "Not allowed"})
  9. })
  10. }
  11. //Serve frontend static files
  12. func ServeStatic(route *gin.Engine) {
  13. route.Use(static.Serve("/", static.LocalFile("./views/public", true)))
  14. route.Use(auth.CORSMiddleware())
  15. api := route.Group("/api")
  16. {
  17. api.GET("/", func(c *gin.Context) {
  18. c.JSON(http.StatusOK, gin.H{
  19. "message": "pong",
  20. })
  21. })
  22. }
  23. }

Go版本是go1.18.1 linux/amd64

"axios": "^0.24.0",
"react": "^18.1.0"

英文:

I have run into a problem implementing cross origin resource sharing in the development environment, between a react front end and Go-lang Gin-Gonic framework, below is the console log from the browser
CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

Console log from the react application sending a post request

This is the received request from the Go framework, as can be seen, the preflight request is not validated

I have attempted two hacks, one is validating the preflight request and passing a 200 on the react OPTIONS as seen below

  1. func preflight(c *gin.Context) {
  2. c.Header("Access-Control-Allow-Origin", "*")
  3. c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers")
  4. c.JSON(http.StatusOK, struct{}{})
  5. }

This hack was not of help, additionally ,i included a middleware with a wildcard domain in the access control allow origin, as well as with http://localhost:3000 as shown below

  1. func CORSMiddleware() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. c.Header("Access-Control-Allow-Origin", "*")
  4. c.Header("Access-Control-Allow-Credentials", "true")
  5. c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
  6. c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")
  7. if c.Request.Method == "OPTIONS" {
  8. c.AbortWithStatus(204)
  9. return
  10. }
  11. c.Next()
  12. }
  13. }

I also tried the gin cors package as shown here github.com/gin-contrib/cors but the request is still being blocked

CORS是跨源资源共享的缩写,React和Gin-Gonic Gin是两个框架的名称。

  1. These are part of my routes
  2. r := gin.Default()
  3. //r := gin.New()
  4. config := cors.DefaultConfig()
  5. config.AllowOrigins = []string{"*"}
  6. // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
  7. // config.AllowAllOrigins = true
  8. r.Use(cors.New(config))
  9. //system routes
  10. router.NotFound(r)
  11. router.NoMethods(r)
  12. //static routes
  13. router.ServeStatic(r)
  14. Methods
  15. func NotFound(route *gin.Engine) {
  16. route.NoRoute(func(c *gin.Context) {
  17. c.JSON(404, gin.H{"msg": "Not Found"})
  18. })
  19. }
  20. func NoMethods(route *gin.Engine) {
  21. route.NoMethod(func(c *gin.Context) {
  22. c.JSON(405, gin.H{"msg": "Not allowed"})
  23. })
  24. }
  25. //Serve frontend static files
  26. func ServeStatic(route *gin.Engine) {
  27. route.Use(static.Serve("/", static.LocalFile("./views/public", true)))
  28. route.Use(auth.CORSMiddleware())
  29. api := route.Group("/api")
  30. {
  31. api.GET("/", func(c *gin.Context) {
  32. c.JSON(http.StatusOK, gin.H{
  33. "message": "pong",
  34. })
  35. })
  36. }

The go version is go version go1.18.1 linux/amd64

  1. "axios": "^0.24.0",
  2. "react": "^18.1.0",

答案1

得分: 1

尝试将CORS中间件移动到handleFunc之前。

示例:

  1. func (h *Handler) InitRoutes() *gin.Engine {
  2. router := gin.New()
  3. router.Use(h.setHeaders)
  4. router.GET("/", h.getRecordsByFilter)
  5. router.GET("/:uuid", h.getRecordByUuid)
  6. router.POST("/", h.createRecord)
  7. router.PUT("/:uuid", h.updateRecord)
  8. router.DELETE("/:uuid", h.deleteRecord)
  9. return router
  10. }

请注意,这是一个示例代码片段,你需要根据自己的实际情况进行相应的修改。

英文:

Try to move CORS middleware before your handleFunc

Example:

  1. func (h *Handler) InitRoutes() *gin.Engine {
  2. router := gin.New()
  3. router.Use(h.setHeaders)
  4. router.GET("/", h.getRecordsByFilter)
  5. router.GET("/:uuid", h.getRecordByUuid)
  6. router.POST("/", h.createRecord)
  7. router.PUT("/:uuid", h.updateRecord)
  8. router.DELETE("/:uuid", h.deleteRecord)
  9. return router
  10. }

答案2

得分: 0

问题出在来自React前端的凭据上。

handleSubmit(event) {
const {email,password} = this.state;
axios.post("http://localhost:3000/auth/register",
{email: email, password: password},{
withCredentials: true}).then(response => {
console.log("registration res", response);
console.log("response data",response.data);
}).catch(error => {
console.log("registration error", error);
});

  1. event.preventDefault();

}

英文:

The problem was with credentials true from the react front-end

  1. handleSubmit(event) {
  2. const {email,password} = this.state;
  3. axios.post("http://localhost:3000/auth/register",
  4. {email: email, password: password},{
  5. withCredentials: true}).then(response => {
  6. console.log("registration res", response);
  7. console.log("response data",response.data);
  8. }).catch(error => {
  9. console.log("registratino error", error);
  10. });
  11. event.preventDefault();
  12. }

huangapple
  • 本文由 发表于 2022年5月10日 14:56:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72181878.html
匿名

发表评论

匿名网友

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

确定