0

I'm working on very basic web app where the server is running on localhost:12345 and client runs on localhost:3000. I'm doing this because, I wrote an actual app and there is cors issue in the production. So I started to drill down to the basic and fix the issue. But I failed. My backend is in 'go'. Here is the 1st html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>This is page1</title>
  </head>
  <body>
    Hi this is page1

    <a href="index2.html" id='link'>About this web app</a>
  </body>



</html>

Here is the second html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript" src='jquery.js'>

    </script>
  </head>
  <body>
    This is page2
  </body>
  <script type="text/javascript">
    $.ajax({
      type: 'GET',
      url: 'http://localhost:12345/people',
      contentType: 'application/json',
      success: function(response){
        alert(response);
      },
      error: function(err){
        alert(JSON.stringify(err));
      }
    })
  </script>
</html>

And finally the backend code:

package main

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

type Person struct {
    ID        string   `json:"id,omitempty"`
    Firstname string   `json:"firstname,omitempty"`
    Lastname  string   `json:"lastname,omitempty"`
    Address   *Address `json:"address,omitempty"`
}

type Address struct {
    City  string `json:"city,omitempty"`
    State string `json:"state,omitempty"`
}

var people []Person

func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for _, item := range people {
        if item.ID == params["id"] {
            json.NewEncoder(w).Encode(item)
            return
        }
    }
    json.NewEncoder(w).Encode(&Person{})
}


func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
    json.NewEncoder(w).Encode(people)
}

func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    var person Person
    _ = json.NewDecoder(req.Body).Decode(&person)
    person.ID = params["id"]
    people = append(people, person)
    json.NewEncoder(w).Encode(people)
}

func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for index, item := range people {
        if item.ID == params["id"] {
            people = append(people[:index], people[index+1:]...)
            break
        }
    }
    json.NewEncoder(w).Encode(people)
}

func main() {
    router := mux.NewRouter()
    people = append(people, Person{ID: "1", Firstname: "Nic", Lastname: "Raboy", Address: &Address{City: "Dublin", State: "CA"}})
    people = append(people, Person{ID: "2", Firstname: "Maria", Lastname: "Raboy"})
    fmt.Println( people);
    router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
    router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
    router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST")
    router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE")

   headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

// start server listen
// with error handling
log.Fatal(http.ListenAndServe(":" + os.Getenv("PORT"), handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}
  • 1
    I don't see any CORS handling in above code snippets. Share your code snippet you have tried. Also refer this [SO post](https://stackoverflow.com/questions/40985920/making-golang-gorilla-cors-handler-work), it would give you a start point. – jeevatkm Jun 19 '17 at 23:59
  • @jeevatkm Do we need to have cors handler even when app is running locally? –  Jun 20 '17 at 00:03
  • I believe your question is `How to tackle Cors issue on local system?` and your description has `I wrote an actual app and there is cors issue in the production`. So if you're not using CORS then what is an issue? Am I missing any? – jeevatkm Jun 20 '17 at 00:06
  • @jeevatkm `corsObj:=handlers.AllowedOrigins([]string{"*"})` I have added this to my main function. I don't know if that's the way to do it. –  Jun 20 '17 at 00:11
  • "there is cors issue". What's the actual error? It'd help if you posted the errors from the browser console. – david25272 Jun 20 '17 at 00:11
  • @david25272 XMLHttpRequest cannot load http://localhost:12345/people. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. –  Jun 20 '17 at 00:12
  • Did you read [SO Post](https://stackoverflow.com/questions/40985920/making-golang-gorilla-cors-handler-work) I mentioned in my first comment regarding CORS. It has all the information required for implementation. – jeevatkm Jun 20 '17 at 00:26
  • @jeevatkm yes, I did. I added the cors handler, but it is still the same. –  Jun 20 '17 at 00:27
  • Good you added it. Are you sending an appropriate HTTP headers while sending a request? Refer to this [SO post](https://stackoverflow.com/a/40987420/1343356), testing via `curl` cmd. – jeevatkm Jun 20 '17 at 00:32
  • @jeevatkm `curl -H "Origin: http://localhost:3000" -H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: X-Requested-With" -X OPTIONS --verbose http://localhost:12345/people * Trying ::1... * Connection failed * connect to ::1 port 12345 failed: Connection refused * Trying 127.0.0.1... * Connection failed * connect to 127.0.0.1 port 12345 failed: Connection refused * Failed to connect to localhost port 12345: Connection refused * Closing connection 0 curl: (7) Failed to connect to localhost port 12345: Connection refused` I don't know what else to add. –  Jun 20 '17 at 01:30
  • It seems your server is not running on `localhost:12345`. Also why you have two `http.ListenAndServe` in above code snippet? You just copy and paste without understanding what that line means. – jeevatkm Jun 20 '17 at 01:44
  • @jeevatkm oops! I didn't notice that. `log.Fatal(http.ListenAndServe(":12345", handlers.CORS(originsOk, headersOk, methodsOk)(router)))` The issue still remains. As usual postman is doing fine. –  Jun 20 '17 at 02:23
  • Try `originsOk := handlers.AllowedOrigins([]string{"*"})` – david25272 Jun 20 '17 at 02:53
  • @david25272 I tried but it didn't work. I found a work around. (https://github.com/rs/cors/blob/master/README.md) –  Jun 20 '17 at 03:01

1 Answers1

1

Ok, The solution for above problem is at this link Go Cors Handler. It does the trick.