【错误记录/html】Response to preflight request doesn‘t pass access control check: No ‘Access-Control-Allow

编程知识 更新时间:2023-04-06 10:54:30

错误详情

  • 在使用ajaxhttp服务器请求时,出现以下错误:
    Response to preflight request doesn't pass access control check: 
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    
  • 请求如下:
    $.ajax({
        url: "http://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
    }
    
    js
    function GetRandName() {
        $.ajax({
            url: "http://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!");
            }
        });
    }
    

更多推荐

【错误记录/html】Response to preflight request doesn‘t pass access control check: No ‘

本文发布于:2023-04-06 10:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/d97e5e284f844732cd5580c84f3b7d59.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   preflight   request   Response   pass

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 49165文章数
  • 14阅读数
  • 0评论数