For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
*
usehttps://www.myotherdomain.com
– pechar Jun 9 '17 at 8:30