如何解决本地系统上的CORS问题?

huangapple go评论105阅读模式
英文:

How to tackle Cors issue on local system?

问题

我正在开发一个非常基本的 Web 应用程序,其中服务器运行在 localhost:12345,客户端运行在 localhost:3000。我这样做是因为我写了一个实际的应用程序,在生产环境中存在跨域问题。所以我开始从基础开始解决这个问题。但是我失败了。我的后端是用 Go 编写的。这是第一个 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>

这是第二个 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>

最后是后端代码:

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)))
}

以上是你提供的内容的翻译。

英文:

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:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;title&gt;This is page1&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
Hi this is page1
&lt;a href=&quot;index2.html&quot; id=&#39;link&#39;&gt;About this web app&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;

Here is the second html:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;title&gt;&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot; src=&#39;jquery.js&#39;&gt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
This is page2
&lt;/body&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
$.ajax({
type: &#39;GET&#39;,
url: &#39;http://localhost:12345/people&#39;,
contentType: &#39;application/json&#39;,
success: function(response){
alert(response);
},
error: function(err){
alert(JSON.stringify(err));
}
})
&lt;/script&gt;
&lt;/html&gt;

And finally the backend code:

package main
import (
&quot;encoding/json&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;fmt&quot;
&quot;github.com/gorilla/mux&quot;
&quot;github.com/gorilla/handlers&quot;
)
type Person struct {
ID        string   `json:&quot;id,omitempty&quot;`
Firstname string   `json:&quot;firstname,omitempty&quot;`
Lastname  string   `json:&quot;lastname,omitempty&quot;`
Address   *Address `json:&quot;address,omitempty&quot;`
}
type Address struct {
City  string `json:&quot;city,omitempty&quot;`
State string `json:&quot;state,omitempty&quot;`
}
var people []Person
func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for _, item := range people {
if item.ID == params[&quot;id&quot;] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&amp;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(&amp;person)
person.ID = params[&quot;id&quot;]
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[&quot;id&quot;] {
people = append(people[:index], people[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(people)
}
func main() {
router := mux.NewRouter()
people = append(people, Person{ID: &quot;1&quot;, Firstname: &quot;Nic&quot;, Lastname: &quot;Raboy&quot;, Address: &amp;Address{City: &quot;Dublin&quot;, State: &quot;CA&quot;}})
people = append(people, Person{ID: &quot;2&quot;, Firstname: &quot;Maria&quot;, Lastname: &quot;Raboy&quot;})
fmt.Println( people);
router.HandleFunc(&quot;/people&quot;, GetPeopleEndpoint).Methods(&quot;GET&quot;)
router.HandleFunc(&quot;/people/{id}&quot;, GetPersonEndpoint).Methods(&quot;GET&quot;)
router.HandleFunc(&quot;/people/{id}&quot;, CreatePersonEndpoint).Methods(&quot;POST&quot;)
router.HandleFunc(&quot;/people/{id}&quot;, DeletePersonEndpoint).Methods(&quot;DELETE&quot;)
headersOk := handlers.AllowedHeaders([]string{&quot;X-Requested-With&quot;})
originsOk := handlers.AllowedOrigins([]string{os.Getenv(&quot;ORIGIN_ALLOWED&quot;)})
methodsOk := handlers.AllowedMethods([]string{&quot;GET&quot;, &quot;HEAD&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;OPTIONS&quot;})
// start server listen
// with error handling
log.Fatal(http.ListenAndServe(&quot;:&quot; + os.Getenv(&quot;PORT&quot;), handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}

答案1

得分: 1

好的,以下是翻译好的内容:

好的,上述问题的解决方案在此链接中:Go Cors Handler。它可以解决这个问题。

英文:

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

huangapple
  • 本文由 发表于 2017年6月20日 07:52:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44641615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定