学无先后,达者为师

网站首页 编程语言 正文

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

作者:o0o_-_ 更新时间: 2022-03-14 编程语言

错误详情

  • 在使用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)
    }
    
    在这里插入图片描述

另一种方法

  • 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!");
            }
        });
    }
    

原文链接:https://blog.csdn.net/qq_33446100/article/details/107992701

栏目分类
最近更新