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

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

Axios 前端到 Golang 后端 CORS 問題

Axios 前端到 Golang 后端 CORS 問題

Go
慕標琳琳 2022-05-23 16:55:44
目前我對 CORS 失去了理智。我有一個 Vue.js 應用程序,它使用 Axios 將數據發布到 Golang 服務(使用 Gorilla Mux 和 Handlers)。兩個應用程序都在同一臺主機上運行。Axios 調用如下所示:const axios = require('axios');const options = {    url: 'http://' + window.location.hostname + ':4002',    method: 'POST',    headers: {        'Accept': 'application/json',                    'Content-Type': 'application/json;charset=UTF-8'    },    data: {        MyField1: "MyData1",        MyField2: {            MyField3: "MyData2"        }    }};axios(options)    .then(response => {        console.log(response.status);    });Golang 服務器如下所示:func main() {    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})    originsOk := handlers.AllowedOrigins([]string{"*"})    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})    router := mux.NewRouter()    router.HandleFunc("/", HandleRequest).Methods("POST", "OPTIONS")    log.Fatal(http.ListenAndServe(":4002", handlers.CORS(originsOk, headersOk, methodsOk)(router)))}func HandleRequest(w http.ResponseWriter, r *http.Request) {    ...}這是數小時搜索如何使其工作的結果。我大量引用了這個答案,并在使用 CURL 進行測試時收到以下信息(以及其他冗余信息):< HTTP/1.1 200 OK< Access-Control-Allow-Headers: X-Requested-With< Access-Control-Allow-Origin: *< Date: Sun, 29 Mar 2020 23:32:28 GMT< Content-Length: 0這讓我相信一切都應該正常工作,但我仍然在 Firefox 的網絡查看器中看到 403 并在控制臺中看到以下內容:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip>:4002/. (Reason: CORS request did not succeed).Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip>:4002/. (Reason: CORS request did not succeed).Error: Network Error我能找到的所有信息都讓我相信我此時不應該看到這個錯誤——任何幫助都將不勝感激。
查看完整描述

1 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

最后通過將 Go 代碼更改為以下內容來解決此問題:


cors := handlers.CORS(

    handlers.AllowedHeaders([]string{"content-type"}),

    handlers.AllowedOrigins([]string{"*"}),

    handlers.AllowCredentials(),

)


router := mux.NewRouter()

router.HandleFunc("/", HandleRequest).Methods("POST", "OPTIONS")


router.Use(cors)


log.Fatal(http.ListenAndServe(":4002", (router)))


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 269 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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