This answer 关于静态到静态 (file://-> file://) 指出网络服务器 (http://) 可用于在不违反 CORS 的情况下将文件提供给本地静态页面 (file://) . this answer 指出,当从网络服务器向静态页面发送数据时,必须使用 null
header 。但是下面两行都不起作用,那么我该怎么做呢?
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:])
}
这会编译但会抛出客户端错误:跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/aardvark/posts 的远程资源。 (原因:缺少 CORS header “Access-Control-Allow-Origin”)
最佳答案
写完这个问题后,我绝望地想尝试最后一件事,结果成功了。
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
如果你觉得这个问题不属于SO,欢迎留言,我会及时撤下。
关于高语 : Setting header to null for a file://to http://request not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966549/