在前端使用react-admin
访问gin
开发的API后端。
从Chrome浏览器访问网址时:
从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
由于前端和后端处于不同的起源(分别为localhost:3000和localhost:8080),因此您需要在后端设置CORS以允许localhost:3000访问它。
在服务器端应用程序中设置访问控制允许响应的原始标头将解决问题。
加,
'Access-Control-Allow-Origin: http://localhost:3000' or
'Access-Control-Allow-Origin: *'
在您的服务器端代码中。
你应该添加一个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()
}
}
}