【问题标题】:Why get 403 forbidden when get API data?为什么在获取 API 数据时会出现 403 禁止?
【发布时间】:2018-06-13 08:45:56
【问题描述】:

在前端使用react-admin访问gin开发的API后端。

从chrome浏览器访问url时:

http://localhost:3000/#/posts

从 chrome Console 收到这条消息:

fetch.js:41 OPTIONS http://localhost:8080/posts?_end=10&_order=DESC&_sort=id&_start=0 403 (Forbidden)

但是如果从浏览器访问上面的uri,它可以返回json结果。

gin开发的API输出中,得到了这条消息:

[GIN] 2018/06/13 - 16:38:16 | 403 |       1.995µs |             ::1 | OPTIONS  /posts?_end=10&_order=DESC&_sort=id&_start=0

【问题讨论】:

    标签: reactjs api gwt-gin


    【解决方案1】:

    由于前端和后端位于不同的来源(分别为 localhost:3000 和 localhost:8080),因此您需要在后端设置 CORS 以允许 localhost:3000 访问它。

    https://github.com/gin-contrib/cors 看起来像那个票。

    【讨论】:

      【解决方案2】:

      在您的服务器端应用程序中为响应设置访问控制允许来源标头将解决此问题。

      添加,

      'Access-Control-Allow-Origin: http://localhost:3000' or
      
      'Access-Control-Allow-Origin: *' 
      

      在您的服务器端代码中。

      【讨论】:

        【解决方案3】:

        你应该添加一个 CORSmiddleware

        main.go:

        r := gin.Default()
        r.Use(CORSMiddleware())
        

        CORSM中间件:

        func CORSMiddleware() gin.HandlerFunc {
            return func(c *gin.Context) {
                c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
                c.Writer.Header().Set("Access-Control-Max-Age", "86400")
                c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
                c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
                c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
                c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
                if c.Request.Method == "OPTIONS" {
                    c.AbortWithStatus(200)
                } else {
                    c.Next()
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-18
          • 1970-01-01
          • 2021-01-28
          • 2022-07-15
          • 2022-08-18
          • 2011-06-24
          相关资源
          最近更新 更多