3

My API is served using the Echo framework. When I do a fetch call from my React app, I get

Access to fetch at 'http://localhost:8080/myAPI' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

even though I'm setting up Echo like this:

    srv := echo.New()
    srv.HideBanner = true
    srv.Use(middleware.Logger())

    srv.Use(middleware.CORS())

I tried the following, but I get the same results:

var (
    // DefaultCORSConfig is the default CORS middleware config.
    DefaultCORSConfig = middleware.CORSConfig{
        Skipper:      middleware.DefaultSkipper,
        AllowOrigins: []string{"*"},
        AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete, http.MethodOptions},
        AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAccessControlAllowOrigin, echo.HeaderAccessControlAllowMethods},
    }
)

srv.Use(middleware.CORSWithConfig(DefaultCORSConfig))

In the response, I don't see the access-control-allow-origin header. I get the same results even if I put localhost:3000 in AllowOrigins

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • Can you check with `curl -X OPTIONS` to see whether the header is actually sent? You might have to add `http.MethodOptions` to `AllowMethods`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#preflighted_requests_in_cors – Zyl Nov 03 '21 at 22:22
  • 1
    With ```curl -X OPTIONS``` I get ```{"message":"Method Not Allowed"}``` – user2233706 Nov 03 '21 at 22:28
  • There is your problem. Add `http.MethodOptions` to `AllowMethods`. Read up a bit about pre-flight requests. – Zyl Nov 03 '21 at 22:30
  • I get the same error as before, both with fetch and curl. I updated the code with ```AllowMethods``` – user2233706 Nov 03 '21 at 22:42
  • https://github.com/labstack/echo/issues/1040 try adding a trailing slash to your request - if that works, maybe something like `e.Pre(middleware.AddTrailingSlash())` can fix it for you – erik258 Nov 03 '21 at 23:55
  • Good find, but that doesn't help either. – user2233706 Nov 04 '21 at 00:03
  • The `Pre` method is executed before `router.Find`, and after `Use` method, you need to use `Pre` to add CORS processing. Intercept the Option request before the router matches and return 204, otherwise the router returns 405. – eudore Nov 04 '21 at 00:28

1 Answers1

0

The issue was that echo.New() was called again somewhere else in the code, thus wiping out the call to srv.Use(middleware.CORS()), which is all you need to allow cross origin calls.

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • 1
    Beware that `middleware.CORS()` is an *allow-all* policy, essentially disabling CORS. The server becomes vulnerable to XSS attacks. – rustyx Nov 04 '21 at 07:10