v v
v v

Reputation: 653

Why get 403 forbidden when get API data?

Using react-admin at front-end to access gin developed API back-end.

When access URL from Chrome browser:

http://localhost:3000/#/posts

Got this message from Chrome Console:

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

But if access the URI above from browser, it can return JSON result.

From the gin developed API output, got this message:

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

Upvotes: 0

Views: 11187

Answers (3)

Jason Chang
Jason Chang

Reputation: 44

You should add a 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()
        }
    }
}

Upvotes: -1

Rohith Murali
Rohith Murali

Reputation: 5669

Setting the access control allow origin header for the response in your server side application will fix the issue.

Add,

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

'Access-Control-Allow-Origin: *' 

in your serrver side code.

Upvotes: -1

AKX
AKX

Reputation: 168986

Since the frontend and the backend are at different origins (localhost:3000 and localhost:8080 respectively), you'll need to set up CORS on the backend side to allow localhost:3000 to access it.

https://github.com/gin-contrib/cors looks like the ticket for that.

Upvotes: -1

Related Questions