AJAX vs GO.

396 views
Skip to first unread message

emmanuel...@upperlink.ng

unread,
Nov 30, 2015, 10:10:01 AM11/30/15
to golang-nuts
My go is returning 404 with Error "XMLHttpRequest cannot load http://localhost:8080/api/user. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I'm sure it is from my backend "GO", but i've try all possible means to get this done. Below is my Go source code, and I'm using AngularJS to consume the API endpoints.

package main

import (
    "fmt"
    "net/http"
    "encoding/json"
    "github.com/gorilla/mux"
    "log"
)

type UserInfo struct{
    FirstName, LastName, MiddleName string
}

type AllUsers struct{
    Users []UserInfo
}

type Error struct{
    Message string
}

func User(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    decoder := json.NewDecoder(r.Body)
    var user_info UserInfo
    err := decoder.Decode(&user_info)
      if(err != nil){
          panic(w, r)
          return
      }
      fmt.Println(user_info.FirstName)
  //  w.Write([]byte("Hello"));
}

func panic(w http.ResponseWriter, r * http.Request){
  w.Header().Set("Content-Type", "application/json")
  w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  w.Header().Set("Access-Control-Allow-Origin", "*")

  ErrorSlice := Error {
    Message : "Invalid JSON Request",
  }

  output,_ := json.Marshal(ErrorSlice)
  log.Println(string(output))

  w.Write([]byte(output))
}

func main(){
    routes := mux.NewRouter()
    routes.HandleFunc("/api/user", User).Methods("GET")
    http.Handle("/", routes)
    http.ListenAndServe(":8080", nil)
}

Please looking forward to hearing from any of you Guys.

Thanks in advance.

Andrew Austin

unread,
Nov 30, 2015, 10:21:54 AM11/30/15
to emmanuel...@upperlink.ng, golang-nuts
For CORS requests, browsers will first send an OPTIONS request that the server should respond with the access control headers for the resource. Your router is only configured to respond to GET requests on /api/users. You should write a handler to handle the OPTIONS request.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

emmanuel...@upperlink.ng

unread,
Nov 30, 2015, 11:12:28 AM11/30/15
to golang-nuts, emmanuel...@upperlink.ng
Thanks so much. I really appreciate your effort, but one more thing. I was trying to send some JSON data using AngularJS Request, but cannot grab the JSON from the r.body in go, but if i send my JSON via CURL, I would be able to grab it, I've been fighting against this issue non-stop, haven't figure out what could be the problem. I'm i not doing right? Looking forward to hearing from you. Thanks in advance.

package main

import (
    "fmt"
    "net/http"
    "encoding/json"
    "log"
)

type UserInfo struct{
    FirstName string "json:FirstName"
    LastName string "json:LastName"
    MiddleName string "json:MiddleName"
}

type AllUsers struct{
    Users []UserInfo
}

type Error struct{
    Message string
}

type Route struct{
    Name string
    Method string
    Pattern string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
    Route{
      "Index",
      "GET",
      "/",
      Index,
    },
    Route{
        "User",
        "POST",
        "/api/user",
        User,
    },
}

func Index(w http.ResponseWriter, r *http.Request){

}

func User(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    log.Println(*&r.Body)
    decoder := json.NewDecoder(r.Body)
    var user_info UserInfo
    err := decoder.Decode(&user_info)
      if(err != nil){
          panic(w, r)
          log.Println(err)
          return
      }
      fmt.Println(user_info.FirstName)
      w.Write([]byte("Hello"));
}

func panic(w http.ResponseWriter, r * http.Request){
  w.Header().Set("Content-Type", "application/json")
  w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  w.Header().Set("Access-Control-Allow-Origin", "*")

  ErrorSlice := Error {
    Message : "Invalid JSON Request",
  }

  output,_ := json.Marshal(ErrorSlice)
  //log.Println(string(output))

  w.Write([]byte(output))
}

func APIDescribe(w http.ResponseWriter, r *http.Request){
  w.Header().Set("Content-Type", "application/json")
  w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  w.Header().Set("Access-Control-Allow-Origin", "*")
}

func main(){
    routes := mux.NewRouter()
    routes.HandleFunc("/api/user", User).Methods("GET", "OPTIONS")
    http.Handle("/", routes)
    http.ListenAndServe(":8080", nil)
}


Reply all
Reply to author
Forward
0 new messages