reactjs 为什么在获取API数据时得到403禁止?

jecbmhm3  于 2023-02-18  发布在  React
关注(0)|答案(3)|浏览(239)

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

当从chrome浏览器访问url时:
网址:http://localhost:3000
从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
fdx2calv

fdx2calv1#

由于前端和后端位于不同的起点(分别为localhost:3000和localhost:8080),因此您需要在后端设置CORS以允许localhost:3000访问它。
https://github.com/gin-contrib/cors看起来就像是那张票。

xdnvmnnf

xdnvmnnf2#

在服务器端应用程序中为响应设置访问控制allow origin标头将解决此问题。
添加,

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

'Access-Control-Allow-Origin: *'

在服务器端代码中。

imzjd6km

imzjd6km3#

您应该添加一个CORS中间件
main.go:

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

CORBA中间件:

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

相关问题