【发布时间】:2017-11-22 07:44:04
【问题描述】:
我正在开发非常基本的 Web 应用程序,其中服务器在 localhost:12345 上运行,客户端在 localhost:3000 上运行。我这样做是因为,我写了一个实际的应用程序,并且在生产中存在 cors 问题。所以我开始深入研究基本并解决问题。但我失败了。我的后端在“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)))
}
【问题讨论】:
-
我在上面的代码 sn-ps 中没有看到任何 CORS 处理。分享您尝试过的代码 sn-p。也可以参考这个SO post,它会给你一个起点。
-
@jeevatkm 即使应用程序在本地运行,我们是否也需要有 cors 处理程序?
-
我相信你的问题是
How to tackle Cors issue on local system?,你的描述是I wrote an actual app and there is cors issue in the production。因此,如果您不使用 CORS,那么有什么问题?我错过了什么吗? -
@jeevatkm
corsObj:=handlers.AllowedOrigins([]string{"*"})我已将此添加到我的主要功能中。我不知道这是否是这样做的。 -
“存在 cors 问题”。实际的错误是什么?如果您从浏览器控制台发布错误会有所帮助。
标签: javascript jquery html go cors