关于静态到静态(file://->file://)的答案表明,可以使用网络服务器(http://)将文件提供到本地静态页面(file://),而不会违反CORS。当将数据从Web服务器发送到静态页面时,null必须使用标头。但是下面的两行都不起作用,那我该怎么办?
null
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 tow.Header().Add
./main.go:42: cannot use nil as type string in argument tow.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)
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)
写下这个问题后,我想绝望地尝试最后一件事,它奏效了。
func handler(w http.ResponseWriter, r *http.Request) { w.Header().Add("Access-Control-Allow-Origin", "null") fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) }
您应该将字符串设置为"null",而不是空字符串""或nil
"null"
""
nil
如果您认为这个问题不属于某个问题,请发表评论,我会尽快将其删除。