#Fixing CORS error

9 messages · Page 1 of 1 (latest)

sharp bough
#

I have a server implemented in net/http with a single POST endpoint, whenever I am trying to hit it from my react code I get a 405 on my pre-flight request, what am I missing?
Here is the implementation of my router package

package router

import (
        "net/http"
        "time"

        "github.com/onlinejudge95/Dicehub/backend/internal/config"
        "github.com/onlinejudge95/Dicehub/backend/internal/handler"
        "github.com/onlinejudge95/Dicehub/backend/internal/middleware"
)

func NewHTTPRouter(conf config.ServerConfig) *http.Server {
        router := http.NewServeMux()

        router.HandleFunc("POST /api/profile", middleware.EnableCors(handler.CreateProfile))

        return &http.Server{
                Addr:         conf.BindAddress,
                ReadTimeout:  10 * time.Second,
                WriteTimeout: 10 * time.Second,
                Handler:      router,
        }
}

Here is the implementation of my EnableCors middleware

package middleware

import (
        "log/slog"
        "net/http"
)

func EnableCors(next http.HandlerFunc) http.HandlerFunc {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                w.Header().Set("Access-Control-Allow-Origin", "*")
                w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
                w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
                slog.Info("Inside Cors handler")

                if r.Method == http.MethodOptions {
                        slog.Info("Received a preflight request")
                        w.WriteHeader(http.StatusOK)
                        return
                }

                next.ServeHTTP(w, r)
        })
}
worthy chasm
#

CORS happens on OPTIONS requests

#

your router does not handle those

sharp bough
#

any way i can define multiple methods in the pattern string in my router

#

I am using 1.22+ go

worthy chasm
#

if you want a blanket allowance on cors, you can setup an OPTIONS request on / and just send those headers

sharp bough
#

Can you provide a example for the above?

worthy chasm
#

a handler on / is called for all paths

sharp bough
#

@worthy chasm it defeats the purpose as I still have to manually set the corresponding headers in every request.
As I asked earlier is there a way to handle cors like middleware?