获取API数据时为什么禁止403?

问题描述 投票:0回答:3

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

从Chrome浏览器访问网址时:

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 gin
3个回答
0
投票

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

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


0
投票

在服务器端应用程序中设置访问控制允许响应的原始标头将解决问题。

加,

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

'Access-Control-Allow-Origin: *' 

在您的服务器端代码中。


0
投票

你应该添加一个CORSmiddleware

main.go:

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

CORSMiddleware:

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()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.