Reputation: 167
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))
Upvotes: 2
Views: 333
Reputation: 160
CORS only happens on the browser. Browser sends a preflight request whose method is OPTION to check if it is allowed to send the original requests.
If you use the following code, it works. You do not need any extra CORS setting. Just remove the other codes regarding CORS.
Backend:
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
"net/http"
"os"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "9000" // Default port if not specified
}
router := httprouter.New()
router.GET("/upload", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
writer.Write([]byte("test body"))
})
handler := cors.AllowAll().Handler(router)
fmt.Println(http.ListenAndServe(":"+port, handler))
}
Frontend
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
fetch("http://localhost:9000/upload")
</script>
</head>
<body>
</body>
</html>
Response: Succes Case
If you replace last two lines in main.go with the following line, you will get CORS error again.
fmt.Println(http.ListenAndServe(":"+port, router))
Upvotes: 1