feat: add CORS middleware to backend server
Add cross-origin resource sharing support to the backend API to fix frontend console errors when accessing resources from different origins. The middleware handles preflight requests and includes necessary CORS headers for API endpoints. Fixes: Cross-Origin Request Blocked error
This commit is contained in:
@@ -15,6 +15,25 @@ type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// CORS middleware for allowing cross-origin requests
|
||||
func corsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Allow requests from any origin during development
|
||||
// In production, you would specify allowed origins
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
// Handle preflight requests
|
||||
if r.Method == "OPTIONS" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
storage *storage.Storage
|
||||
host string
|
||||
@@ -42,10 +61,13 @@ func (s *Server) Start() error {
|
||||
// Frontend SPA fallback
|
||||
mux.HandleFunc("/", s.handleFrontend)
|
||||
|
||||
// Wrap with CORS middleware
|
||||
handler := corsMiddleware(mux)
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", s.host, s.port)
|
||||
logger.Infof("Starting server on %s", addr)
|
||||
|
||||
return http.ListenAndServe(addr, mux)
|
||||
return http.ListenAndServe(addr, handler)
|
||||
}
|
||||
|
||||
func (s *Server) handleFiles(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
Reference in New Issue
Block a user