Website using React that works with a Go backend, CORS issue

49 Views Asked by At

I am receiving the following error when I try to submit form credentials through my login form to my Go backend:

"A cross-origin resource sharing (CORS) request was blocked because it was configured to include credentials but the Access-Control-Allow-Credentials response header of the request or the associated preflight request was not set to true."

My GO server works properly if I test it using curl, and my React website form works properly in terms of outputting the correct input when I submit the form, however, they will not work together. I will include the code from my and main.go file. i have tried to set the access-control-allow-creds to true but it still is not working.

`package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type Credentials struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Method is not supported", http.StatusMethodNotAllowed)
        http.Error(w, "test", http.StatusMethodNotAllowed)
        return
    }

    var creds Credentials

    err := json.NewDecoder(r.Body).Decode(&creds)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    w.Header().Set("Content-Type", "application/json")

    fmt.Printf("login attempt username: %v\n", creds)

    json.NewEncoder(w).Encode(creds)
}

func corsHandler(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Set CORS headers
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")            // Allow any origin
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") // Allowed methods
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        w.Header().Set("Access-Control-Allow-Credentials", "true")

        // Check if the request is for CORS preflight
        if r.Method == "OPTIONS" {
            w.WriteHeader(http.StatusOK)
            return
        }

        // Pass down the request to the next handler
        next.ServeHTTP(w, r)
    })
}

func main() {
    fmt.Println("server is running on http://localhost:8080")
    // Use the CORS middleware
    http.Handle("/login", corsHandler(http.HandlerFunc(loginHandler)))
    log.Fatal(http.ListenAndServe(":8080", nil))
}````

0

There are 0 best solutions below