I was writing a blog application which has front end in react + typescript and backend in go iris. I'm doing a get request to fetch blog content. Backend runs at localhost:5000 and node at localhost:3000.But it fails with the error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/getposts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I have already configured CORS in the backend
Cors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"},
AllowedHeaders: []string{"Cache-Control", "X-File-Name", "X-Requested-With", "X-File-Name", "Content-Type", "Authorization", "Set-Cookie", "Cookie"},
Debug: true,
})
authConfig := basicauth.Config{
Users: map[string]string{USER_NAME: PASSWORD},
Realm: "Authorization Required", // defaults to "Authorization Required"
Expires: time.Duration(30) * time.Minute,
}
authentication := basicauth.New(authConfig)
app := iris.New()
app.Use(Cors)
app.Get("/getposts", authentication, GetPostsHandler)
This is how I send request
fetch("http://localhost:5000/getposts", {
method: "get",
credentials: "include",
mode: "cors",
headers: [
["Content-Type", "application/json"],
["Authorization", "Basic " + btoa("Sreyas:password")]
]
})
.then(response => {
if (response.ok) {
response.json().then(rawdata => {
this.setState({ blogdata: rawdata });
});
} else {
console.log("No posts");
this.setState({ blogdata: null });
}
})
.catch(error => {
console.log("Server Error");
this.setState({ blogdata: null });
});
I searched and tried for hours to fix this problem but no luck.