I have a basic go API server that serves up a "job" from the database and returns in in a JSON response with the Access-Control-Allow-Origin: * added to the header.
func GetJob(w http.ResponseWriter, r *http.Request) {
job := Job{}
db, err = gorm.Open("postgres", connString)
if err != nil {
panic("Could not connect to the database")
}
defer db.Close()
vars := mux.Vars(r)
jobID, err := strconv.Atoi(vars["jobid"])
if err != nil {
panic("can't convert string")
}
db.Debug().Where("id = ?", jobID).First(&job)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(&job)
}
This is intended to be read my a client app written in angular dart:
class DataService {
final _headers = {'Content-Type': 'text/plain'};
var jobUrl = 'http://127.0.0.1:9000/job';
final Client _http;
DataService(this._http);
Future<Job> getJob(int id) async {
try{
final response = await _http.get('$jobUrl/$id/');
return new Job.fromJson(_extractData(response));
}
catch (e) {
throw _handleError(e);}
}
On postman I can access it with no issues with the Access-Control-Allow-Origin header also. However, when I call the getJob(1) function from the app, chrome throws an error:
XMLHttpRequest cannot load http://127.0.0.1:9000/job/1/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Any ideas on what I am missing here? Most likely everything.