目前我對 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)))
- 1 回答
- 0 關注
- 269 瀏覽
添加回答
舉報
0/150
提交
取消