2

I have a API-server (gin-gonic) running on localhost:8080. All the typical CORS-Header are set for debugging: When I try to test the API with a simple Frontend (swagger-ui) i get a CORS-error. (swagger is running on localhost:9090)

It works when everything is running on the same domain.

c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

why is this not working. Should the 3 lines not keep all CORS problems away?

Im super curious for actual explanations rather than a plain solution. All resources regarding this (or a good one about CORS) are welcome.

It works fine in Postman or CURL

Errormessage in browser: CORS Error Message

Paul Oskar Mayer
  • 1,107
  • 1
  • 10
  • 22
  • 3
    can you include the error message you get? – Henry Woody Dec 29 '18 at 00:27
  • 1
    *"Should the 3 lines not keep all CORS problems away?"* No. When using [Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin#Syntax) are you also using credentials? If so `"*"` will fail. In this case you should, instead of `*`, pass in the origin. [Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers#Syntax) does not allow `"*"`. – mkopriva Dec 29 '18 at 11:16
  • Thanks for the fast feedback. Screenshot or error attached. – Paul Oskar Mayer Dec 30 '18 at 02:26
  • @mkopriva, i tried it also with c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") Same result – Paul Oskar Mayer Dec 30 '18 at 02:29
  • It doesnt look like there's anything being returned from the request. In fact, it looks like a non-200 HTTP status code. What is the status code being returned from your request? – Adam McGurk Dec 30 '18 at 02:29

1 Answers1

1

When you catch OPTION as Preflight request your server should return success. I cannot find return in your provided code.

Also you can try to use https://github.com/rs/cors

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    cors "github.com/rs/cors/wrapper/gin"
)

func main() {
    router := gin.Default()

    router.Use(cors.Default())
    router.GET("/", func(context *gin.Context) {
        context.JSON(http.StatusOK, gin.H{"hello": "world"})
    })

    router.Run(":8080")
}
Maxim
  • 2,233
  • 6
  • 16