日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

【錯(cuò)誤記錄/html】Response to preflight request doesn‘t pass access control check: No ‘Access-Control-Allow

作者:o0o_-_ 更新時(shí)間: 2022-03-14 編程語(yǔ)言

錯(cuò)誤詳情

  • 在使用ajaxhttp服務(wù)器請(qǐng)求時(shí),出現(xiàn)以下錯(cuò)誤:
    Response to preflight request doesn't pass access control check: 
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    
  • 請(qǐng)求如下:
    $.ajax({
        url: "http://127.0.0.1/getname",
        type: 'GET',
        success: function (data) {
            UpdateNameInput(htmlDomInputID, data);
        },
        error: function () {
            console.log("Get Rand Name Failed!");
        }
    });
    
  • 服務(wù)器為golang實(shí)現(xiàn)

一種解決

  • 查了好多資料,嘗試了好多方法,最終用了這個(gè)_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);
    }
    
    服務(wù)器
    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庫(kù)-cors
  • 使用
    服務(wù)器
    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

欄目分類
最近更新