I built a REST application to serve resources to my Angular application and so far, so good, but I have one issue so far. I don't know if this is an Angular or Go question, but I solved the issue through some changes in Go. Here's a snippet:
(Also, I am using the Gorilla Mux package)
package app
import (
"appengine"
"github.com/gorilla/mux"
"net/http"
)
func init() {
// Create a new router.
r := mux.NewRouter()
// Get a reference to the People Controller.
pc := PeopleController{}
// All of these work fine...
r.Handle("/people", withCORS(appHandler(pc.All))).Methods("GET")
r.Handle("/people", withCORS(appHandler(pc.Create))).Methods("POST")
r.Handle("/people/{id}", withCORS(appHandler(pc.Find))).Methods("GET")
r.Handle("/people/{id}", withCORS(appHandler(pc.Update))).Methods("PUT")
r.Handle("/people/{id}", withCORS(appHandler(pc.Delete))).Methods("DELETE")
// ANY POSTs from from Angular hit this route handler.
// WHY should I have have this handler?
r.Handle("/people", withCORS(appHandler(pc.Create))).Methods("OPTIONS")
}
// Simple wrapper to Allow CORS.
func withCORS(fn appHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
fn(w, r)
}
}
The
appHandler code is pretty much verbatim from
here, BTW. I omitted it from the sample above for brevity.
So I can make a POST without any modifications to /people using something like Postman, and it always works, but when I attempt an Angular POST:
http.post('http://some.url/people', payload).then(function(result) {
// Do something with result...
}, function() {
// Handle error...
});
...it ends up making an
OPTIONS request, and NOT a
POST request. Therefore, I had to add a route handler for "OPTIONS", (r.Handle("/people", withCORS(appHandler(pc.Create))).Methods("OPTIONS")), and it doesn't feel right. Is there something I am missing, or is there a better way to handle this (client or server-side)? Pawel Kozlowski has a great SO explanation
here, but I'm still kind of confused on the Go side.
Thanks!