golang實(shí)現(xiàn)跨域訪問(wèn)的方法
前端通過(guò)Ajax來(lái)獲取服務(wù)器資源時(shí),會(huì)存在跨域問(wèn)題。因?yàn)锳jax只能同源使用(預(yù)防某些惡意行為),所以當(dāng)訪問(wèn)不在同一個(gè)域中的資源時(shí),就會(huì)出現(xiàn)跨域限制。尤其在開發(fā)和測(cè)試時(shí),跨域問(wèn)題會(huì)給前端測(cè)試帶來(lái)非常不便。
不過(guò)CORS(Cross-Origin Resource Sharing,跨域資源共享)解決了這個(gè)問(wèn)題,它背后的基本思想是:使用自定義的HTTP頭部讓瀏覽器與服務(wù)器進(jìn)行溝通,從而決定請(qǐng)求或響應(yīng)是否應(yīng)該成功。CORS需要瀏覽器和服務(wù)器同時(shí)支持。整個(gè)CORS通信過(guò)程,瀏覽器是自動(dòng)完成,而服務(wù)器需要手動(dòng)配置。
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()">請(qǐng)求數(shù)據(jù)</button>
<div id="myDiv"></div>
</body>
</html>
crossorigin.go
package main
import (
"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)
}
當(dāng)從 http://localhost:8000/ 頁(yè)面(ajax.html)通過(guò)ajax訪問(wèn) http://localhost:8000/ajax 時(shí),就會(huì)出現(xiàn)下圖所示的錯(cuò)誤:
解決方法: golang設(shè)置HTTP頭部相當(dāng)簡(jiǎn)單,標(biāo)準(zhǔn)包有現(xiàn)成的方法可以使用。只要在服務(wù)器端的響應(yīng)頭中添加下面一句代碼就可以正常訪問(wèn)了。
w.Header().Set("Access-Control-Allow-Origin", "*")
//"*"表示接受任意域名的請(qǐng)求,這個(gè)值也可以根據(jù)自己需要,設(shè)置成不同域名
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Golong實(shí)現(xiàn)JWT身份驗(yàn)證的詳細(xì)過(guò)程
JWT提供了一種強(qiáng)大而靈活的方法來(lái)處理Web應(yīng)用程序中的身份驗(yàn)證和授權(quán),本教程將引導(dǎo)您逐步實(shí)現(xiàn)Go應(yīng)用程序中的JWT身份驗(yàn)證過(guò)程,感興趣的朋友跟隨小編一起看看吧2024-03-03
Go語(yǔ)言學(xué)習(xí)之結(jié)構(gòu)體和方法使用詳解
這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言中結(jié)構(gòu)體和方法的使用,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Go語(yǔ)言有一定的幫助,需要的可以參考一下2022-04-04

