前端通过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 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)
}

当从http://localhost:8000/页面(ajax.html)通过ajax访问http://localhost:8000/ajax时,就会出现下图所示的错误:

crossorigin
解决方法: golang设置HTTP头部相当简单,标准包有现成的方法可以使用。只要在服务器端的响应头中添加下面一句代码就可以正常访问了。

w.Header().Set("Access-Control-Allow-Origin", "*")
//"*"表示接受任意域名的请求,这个值也可以根据自己需要,设置成不同域名