Reputation: 7792
So I'm trying to use isomorphic-fetch https://www.npmjs.com/package/isomorphic-fetch
I have a server written in go that is giving back JSON data. This is how I'm making the call -
export function fetchDistricts(geoState) {
return function (dispatch) {
dispatch(requestDistricts(geoState));
return fetch(`http://localhost:8100/districts/`)
.then(response => {console.log(response);})
.then(json => {
console.log("json");
});
}
I get this error in the chrome console
Fetch API cannot load http://localhost:8100/districts/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8200' is therefore not allowed access.
This is weird, because in my handler I am doing this
func getDistricts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Header().Set("Access-Control-Allow-Origin", "*")
rows, err := db.Query("SELECT * from districts")
//other code here
Further, this was working
var activitiesDfD = $.ajax({
url: "http://localhost:8100/district/1/activities",
type: "GET",
dataType: "json"
});
$.when(activitiesDfD).then(function(data, textStatus, jqXhr) {
Why would this fail when using the fetch API and how do I get around this?
Edit-
I've now tried this
func getDistricts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
w.WriteHeader(http.StatusOK)
Incorporating the two suggestions below - but the error is the same.
Upvotes: 2
Views: 6302
Reputation: 7792
I ended up using this middleware https://github.com/rs/cors, and that got everything working correctly.
Upvotes: 0
Reputation: 113954
Almost all web browsers reject the origin "*"
. Therefore sending "*"
as the Access-Control-Allow-Origin
header results in a same-origin-policy violation.
Fortunately there is a work-around. If you look at the gin-cors code that handles this, what it does instead is to re-send the "origin"
header sent by the browser. So to make *
work, you'd have to do this:
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
Upvotes: 1