Golang實現CORS例子

CORS

什麼是CORS
大概知道什麼是CORS,偶爾也遇到過,想自己實現個例子

用Golang代碼實現

因爲CORS只要域名,協議,端口之一不一樣就算,我們在本機起兩個web服務,只是監聽端口不一樣

服務1

監聽本機1718端口,在後端渲染了一個頁面,在頁面裏用Ajax訪問服務2(1719端口)

在Ajax請求裏請求成功會在瀏覽器的console裏輸出服務2返回的內容

package main

import (
"flag"
"html/template"
"log"
"net/http"
)


var templ = template.Must(template.New("qr").Parse(templateStr))

func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(":1718", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func QR(w http.ResponseWriter, req *http.Request) {
	templ.Execute(w, req.FormValue("s"))
}

const templateStr = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QR Link Generator</title>
    <script>
        let invocation = new XMLHttpRequest();
        let url = 'http://127.0.0.1:1719';

        function callOtherDomain() {
            alert("callOtherDomain");
            if (invocation) {
                invocation.open('GET', url, true);
                invocation.onreadystatechange = function () {
                    if (invocation.readyState === XMLHttpRequest.DONE && invocation.status === 200) {
                        console.log(invocation.responseText)
                    }
                };
                invocation.send();
            }
        }
        callOtherDomain();
    </script>
</head>
<body>
{{if .}}
<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl={{.}}" />
<br>
{{.}}
<br>
<br>
{{end}}
<form action="/" name=f method="GET">
    <input maxLength=1024 size=70 name=s value="" title="Text to QR Encode">
    <input type=submit value="Show QR" name=qr>
</form>
</body>
</html>
`

服務2

監聽1719端口,只有一個路由就是返回字符串的"hello,world"

語句1是控制能否跨域訪問的關鍵

package main

import (
	"flag"
	"log"
	"net/http"
)


func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(":1719", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func QR(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")  // 語句1
	w.Write([]byte("hello,world"))
}

語句1被註釋的情況

打開瀏覽器訪問服務1在瀏覽器命令行看到如下,可以看到被同源策略阻擋了

	Access to XMLHttpRequest at 'http://127.0.0.1:1719/' from origin 'http://127.0.0.1:1718' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在這裏插入圖片描述

語句1未被註釋的情況

打開瀏覽器訪問服務1在瀏覽器命令行看到服務2成功的返回
成功的打印出了服務2的返回

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章