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

golang http伺服器跨域問題解決

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