GoLang:将文件头设置为null:// to http://请求不起作用 [英] GoLang: Setting header to null for a file:// to http:// request not working

查看:323
本文介绍了GoLang:将文件头设置为null:// to http://请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个关于静态到静态(file:// - > file://)的回答表明,一个web服务器http://)可用于在不违反CORS的情况下将文件提供给本地静态页面(file://)。并且这个答案指出,当从一个web服务器发送数据到一个静态页面时,一个的头必须使用。但是,下面两行都没有工作,所以我该怎么做呢?

  func处理程序(w http.ResponseWriter,r * http.Request){
w.Header()。Add(Access-Control-Allow-Origin,nil)//这一行
fmt.Fprintf(w,我爱%s!,r.URL.Path [1:])
}

错误 ./main.go:42:不能在w.Header()的参数中使用nil作为类型字符串。 b

  func handler(w http.ResponseWriter,r * http.Request){
w.Header()。Add(Access-Control-Allow-Origin, )
fmt.Fprintf(w,你好,我爱%s!,r.URL.Path [1:])
}

这会编译但引发客户端错误:跨源请求被阻止:同源策略不允许读取http处的远程资源://本地主机:8080 /豚/职位。 (原因:缺少CORS头'Access-Control-Allow-Origin')

解决方案

  func处理程序(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,请留下评论,我会立即将其删除。

This answer about static to static (file:// -> file://) states that a webserver (http://) can be used to serve files to a local static page (file://) without violating CORS. And this answer states that when sending data from a webserver to a static page, a header of null must be used. But neither of the two lines below are working, so how do I do it?

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:])
}

returns the error ./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:])
}

This compiles but throws the client side error: 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)

解决方案

After writing up this question, I thought to try one last thing out of desperation, and it worked.

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:])
}

You're supposed to set the string to "null", rather than a null string "" or nil

If you don't think this question belongs on SO, please leave a comment and I'll promptly take it down.

这篇关于GoLang:将文件头设置为null:// to http://请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆