国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

golang實現跨域訪問的方法

2020-04-01 18:50:04
字體:
來源:轉載
供稿:網友

前端通過Ajax來獲取服務器資源時,會存在跨域問題。因為Ajax只能同源使用(預防某些惡意行為),所以當訪問不在同一個域中的資源時,就會出現跨域限制。尤其在開發和測試時,跨域問題會給前端測試帶來非常不便。

不過CORS(Cross-Origin Resource Sharing,跨域資源共享)解決了這個問題,它背后的基本思想是:使用自定義的HTTP頭部讓瀏覽器與服務器進行溝通,從而決定請求或響應是否應該成功。CORS需要瀏覽器和服務器同時支持。整個CORS通信過程,瀏覽器是自動完成,而服務器需要手動配置。

ajax.html

<!doctype html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"     content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <script>    function loadXMLDoc() {      var xmlhttp;      if (window.XMLHttpRequest) {        xmlhttp = new XMLHttpRequest();      }      else {        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");      }      xmlhttp.onreadystatechange = function () {        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {          document.getElementById("myDiv").innerHTML = xmlhttp.responseText;        }      }      xmlhttp.open("GET", "http://127.0.0.1:8000/ajax", true);      xmlhttp.send();    }  </script>  <title>Document</title></head><body>  <h2>cross origin</h2>  <button type="button" onclick="loadXMLDoc()">請求數據</button>  <div id="myDiv"></div></body></html>

crossorigin.go

package mainimport (  "net/http"  "html/template"  "fmt"  "encoding/json")type Message struct {  Name string `json:"name"`  Msg string `json:"msg"`}func main() {  http.HandleFunc("/", Entrance)  http.HandleFunc("/ajax", TestCrossOrigin)  http.ListenAndServe(":8000", nil)}func Entrance(w http.ResponseWriter, r *http.Request) {  t,_:=template.ParseFiles("templates/ajax.html")  t.Execute(w, nil)}func TestCrossOrigin(w http.ResponseWriter, r *http.Request) {  if r.Method == "GET" {    var message Message    message.Name = "benben_2015"    message.Msg = "success"    result, err := json.Marshal(message)    if err != nil {      fmt.Println(err)      return    }    ResponseWithOrigin(w, r, http.StatusOK, result)    return  }}func ResponseWithOrigin(w http.ResponseWriter, r *http.Request, code int, json []byte) {  w.Header().Set("Content-Type", "application/json; charset=utf-8")  w.WriteHeader(code)  w.Write(json)}

當從 http://localhost:8000/ 頁面(ajax.html)通過ajax訪問 http://localhost:8000/ajax 時,就會出現下圖所示的錯誤:

golang,跨域訪問

解決方法: golang設置HTTP頭部相當簡單,標準包有現成的方法可以使用。只要在服務器端的響應頭中添加下面一句代碼就可以正常訪問了。

w.Header().Set("Access-Control-Allow-Origin", "*")//"*"表示接受任意域名的請求,這個值也可以根據自己需要,設置成不同域名

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 芒康县| 罗田县| 天镇县| 温宿县| 永顺县| 青海省| 宣化县| 军事| 驻马店市| 沙洋县| 彭州市| 英超| 太谷县| 金秀| 公主岭市| 大渡口区| 山东省| 称多县| 大渡口区| 阳江市| 龙门县| 苏尼特右旗| 达拉特旗| 武功县| 无棣县| 泽州县| 得荣县| 朝阳区| 尼勒克县| 华坪县| 炉霍县| 阳东县| 南江县| 泸定县| 安图县| 华蓥市| 甘德县| 凭祥市| 抚松县| 山阴县| 清原|