I have a simple server written in Go. I then have a simple Nextjs app that acts as the frontend of my project. The issue is that whenever I try to fetch the backend from the frontend, the normal CORS error pops out.
Now, I know that the frontend does a preflight call with HTTP OPTIONS and it checks headers and so on, but after looking at dozens of StackOverflow posts with what seemed to be a solution, nothing worked.
This is the source code
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type ClassReturn struct {
Errcode int `json:"errcode"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func main() {
r := mux.NewRouter()
router(r)
log.Fatal(http.ListenAndServe(":8000", r))
}
func router(r *mux.Router) {
r.HandleFunc("/get", corsHandler(handleOutput)).Methods("GET", "OPTIONS")
r.HandleFunc("/post", corsHandler(handleOutput)).Methods("POST", "OPTIONS")
}
func corsHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
log.Print("preflight detected: ", r.Header)
w.Header().Add("Connection", "keep-alive")
w.Header().Add("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET, DELETE, PUT")
w.Header().Add("Access-Control-Allow-Headers", "content-type")
w.Header().Add("Access-Control-Max-Age", "86400")
return
} else {
handleOutput(w, r)
}
}
}
func handleOutput(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(ClassReturn{
Errcode: 0,
Message: "stuff endpoint",
Data: r.Method,
})
}
This is the console message I get when fetching the go endpoint (for the get endpoint, but I do get the same for the post endpoint)
localhost/:1 Access to XMLHttpRequest at 'http://localhost:8000/get' 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.
In the network tab I get the failed HTTP Request with GET + Preflight blocked by CORS
Neither a POST nor a GET call works, nor does it if I change the Access-Control-Allow-Origin
from http://localhost:3000
to *
I tried different things, like those
- rs/cors
- github.com/gorilla/handlers
- How to handle preflight CORS requests on a Go server
- Making golang Gorilla CORS handler work
- Enable CORS in Golang
- https://www.stackhawk.com/blog/golang-cors-guide-what-it-is-and-how-to-enable-it/
- CORS on golang server & javascript fetch frontend
- Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
But none of those above have worked.
I have also asked on the Discord server of Go but they prompt me to use these very solutions I have above, which don't work
If anyone knows a possible solution to my issue I would be delighted