亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 服務器上的 CORS 和 javascript 獲取前端

golang 服務器上的 CORS 和 javascript 獲取前端

Go
瀟湘沐 2022-04-20 16:59:44
我有一個 golang HTTP 服務器,其代碼如下:    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {    log.Println("New incoming request")    // Authenticate    if u, p, ok := r.BasicAuth(); ok {      log.Println("Success")      return    }    log.Println("Failed")我從一個 JS 前端調用這個 HTTP 端點,這是一個部署在端口 3000 上的反應應用程序,使用代碼:      fetch('http://localhost:8080/login', {            method: 'post',            headers: {                'Authorization': 'Basic ' + btoa(authHeader),                'Content-Type': 'application/x-www-form-urlencoded',                'Access-Control-Allow-Origin': '*'            },                body: 'A=1&B=2'            })            .then(function (response) {                console.log("Authentication Success")            })            .catch(function (err) {                console.log("Authentication fail", err)            });上面的代碼失敗并顯示以下日志。在服務器端:New incoming requestFailed在瀏覽器上,在開發者工具日志中:Fetch API cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.有人可以幫助解決身份驗證問題嗎?我不確定我是在服務器端遺漏了與 CORS 相關的內容,還是在客戶端進行了錯誤的身份驗證。有什么幫助嗎?謝謝。
查看完整描述

2 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

Access-Control-Allow-Origin: *必須從服務器發送,而不是由客戶端發送。假設您在標準net/http處理程序函數中,請嘗試以下代碼:


func handler(w http.ResponseWriter, r *http.Request) {

    w.Header().Set("Access-Control-Allow-Origin", "*")

    if (r.Method == "OPTIONS") {

        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed

    } else {

        // Your code goes here

    }

}


查看完整回答
反對 回復 2022-04-20
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

首先 - 您需要在處理程序中使用模式:


w.Header().Set("Access-Control-Allow-Origin", "*")

    if (r.Method == "OPTIONS") {

        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed

    } else {

        // Your code goes here

    }

但在此之前,您需要在主“選項”中指定:


router.HandleFunc("/your_route/", your_method).Methods("POST", "OPTIONS")

這是因為您的瀏覽器執行 2 個請求 - 首先檢查使用某些標頭的能力(例如授權),下一步是發布數據


查看完整回答
反對 回復 2022-04-20
  • 2 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號