This answer關於static to static(file:// - > file://)聲明webserver(http://)可用於在不違反CORS的情況下將文件提供給本地靜態頁面(file://)。並且this answer指出,當將數據從Web服務器發送到靜態頁面時,必須使用null
的標題。但是下面兩行都沒有工作,所以我該怎麼做?GoLang:將文件頭設置爲空://對於http://請求不起作用
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", nil) //this line
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
返回錯誤./main.go:42: cannot use nil as type string in argument to w.Header().Add
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "")
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
這編譯,但拋出的客戶端錯誤:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/aardvark/posts. (Reason: CORS header 'Access-Control-Allow-Origin' missing)
Kudos! NULL或缺少值的實現在語言和平臺之間是不同的(即JSON's是'null',Python是'None',Go是'nil')。對於HTTP頭文件,這是純文本格式,因此Go中沒有辦法(也可能不需要)將'nil'轉換爲'null'。 – PieOhPah