I am running a backend server locally and the frontend in a Docker container at localhost:8080
. When I open the front end, I get the following error:
Access to fetch at 'http://localhost:3000/myservice' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have tried setting various headers, including the following:
func (m MyService) initializeRoutes() {
m.router.HandleFunc(VERSION+"/stuff", corsHandler(b.getStuff)).Methods("GET")
}
func corsHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Print("preflight detected: ", r.Header)
w.Header().Add("Connection", "keep-alive")
w.Header().Add("Access-Control-Allow-Origin", "*")
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")
// continue with my method
h(w, r)
}
}
func (m MyService) getStuff(w http.ResponseWriter, r *http.Request) {
//Do what is required
}
However, I am still getting the same error. Does anyone know why and how to fix it?
The issue is with the CORS (Cross-Origin Resource Sharing) policy. The error message indicates that the backend server at http://localhost:3000/myservice
is not including the required Access-Control-Allow-Origin
header in its response. This header is necessary to allow requests from different origins, such as http://localhost:8080
in your case.
To fix this issue, you need to modify your backend server code to include the Access-Control-Allow-Origin
header in the response. You can do this by adding the following line of code inside the corsHandler
function before calling the actual handler function:
w.Header().Set("Access-Control-Allow-Origin", "*")
The updated corsHandler
function should look like this:
func corsHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Print("preflight detected: ", r.Header)
w.Header().Add("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
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")
// continue with my method
h(w, r)
}
}
By setting the Access-Control-Allow-Origin
header to “", you are allowing requests from any origin. If you want to restrict it to only http://localhost:8080
, you can replace "” with that specific origin.
After making this change, restart your backend server and try accessing the frontend again. The error should be resolved, and the frontend should be able to fetch data from the backend without any CORS issues.