admin管理员组文章数量:1794759
【错误记录/html】Response to preflight request doesn‘t pass access control check: No ‘Access
错误详情
- 在使用ajax向http服务器请求时,出现以下错误:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- 请求如下:$.ajax({ url: "127.0.0.1/getname", type: 'GET', success: function (data) { UpdateNameInput(htmlDomInputID, data); }, error: function () { console.log("Get Rand Name Failed!"); } });
- 服务器为golang实现
-
查了好多资料,尝试了好多方法,最终用了这个_StackOverflow
-
即
try { var xhttp = new XMLHttpRequest(); xhttp.open("GET", httpURL + httpGetName, false); xhttp.setRequestHeader("Content-type", "text/html"); xhttp.send(); alert(xhttp.response) } catch (error) { alert(error.message); }服务器
func GetNameHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") randName := "NickName" fmt.Fprintf(w, randName) } -
注意 此种方式可能并不能完全解决 CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
- golang库-cors
- 使用 服务器func StartHttpServer() bool { c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, }) mux := http.NewServeMux() mux.HandleFunc("/getname", GetIDHandler) handler := c.Handler(mux) http.ListenAndServe(addr, handler) return true } jsfunction GetRandName() { $.ajax({ url: "127.0.0.1/getname", type: 'GET', success: function (data) { console.log(data) UpdateNameInput(htmlDomInputID, data.id); }, error: function () { console.log("Get Rand Name Failed!"); } }); }
本文标签: 错误responsepreflightrequesthtml
版权声明:本文标题:【错误记录html】Response to preflight request doesn‘t pass access control check: No ‘Access 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686959893a122417.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论