简体   繁体   English

如何在本地系统上解决Cors问题?

[英]How to tackle Cors issue on local system?

I'm working on very basic web app where the server is running on localhost:12345 and client runs on localhost:3000. 我正在使用非常基本的Web应用程序,其中服务器在localhost:12345上运行,客户端在localhost:3000上运行。 I'm doing this because, I wrote an actual app and there is cors issue in the production. 我这样做是因为,我写了一个实际的应用程序,生产中出现了cors问题。 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: 这是第一个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: 这是第二个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)))
}

Ok, The solution for above problem is at this link Go Cors Handler . 好的,以上问题的解决方案是在此链接转到Cors Handler It does the trick. 它能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM