1. 程式人生 > >golang http服務器跨域問題解決

golang http服務器跨域問題解決

font and http服務器 -s 客戶 run style header() client

func main() {
 
    openHttpListen()
}
 
func openHttpListen() {
    http.HandleFunc("/", receiveClientRequest)
    fmt.Println("go server start running...")
 
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
 
func receiveClientRequest(w http.ResponseWriter, r 
*http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") //允許訪問所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的類型 w.Header().Set("content-type", "application/json") //返回數據格式是json r.ParseForm() fmt.Println("收到客戶端請求: ", r.Form)

測試下來,發現web端發送數據給go服務器是可以收到的,就在go服務器返回數據給client web端的時候,出現了跨域錯誤提示,給http.ResponseWriter.Header() 加這三行代碼即可:

w.Header().Set("Access-Control-Allow-Origin", "*")             //允許訪問所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的類型
w.Header().Set("content-type", "application/json"
) //返回數據格式是json

golang http服務器跨域問題解決