I have a backend in Go on Heroku, and my frontend is being served by another Go app on Heroku. I am trying to make requests to the backend from the frontend and I am getting this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://grafulator.herokuapp.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.
I understand the error, and that it is something I need to set in the backends header for each route. I have tried doing this and it does not solve the problem.
The requests work in Postman to the backend, but the problem comes when I try to make these requests from a web browser, either locally or my frontend served on heroku.
Things I have tried:
router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Access-Control-Request-Method") != "" {
// Set CORS headers
header := w.Header()
header.Set("Access-Control-Allow-Methods", header.Get("Allow"))
header.Set("Access-Control-Allow-Origin", "*")
}
// Adjust status code to 204
w.WriteHeader(http.StatusNoContent)
})
w.Header().Set("Access-Control-Allow-Origin", "*")
func main() {
// BasicAuth username and password
user := ""
pass := ""
port := os.Getenv("PORT")
if port == "" {
port = "9000" // Default port if not specified
}
DefaultUser()
// HTTPRouter Settings and Routes
router := httprouter.New()
router.POST("/login/", BasicAuth(RouteLogin, user, pass))
router.POST("/upload/", JWTAuth(RouteUpload))
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "DELETE", "PUT", "OPTIONS"},
})
fmt.Println(http.ListenAndServe(":"+port, c.Handler(router)))
}
handler := cors.AllowAll().Handler(router)
fmt.Println(http.ListenAndServe(":8081", handler))