gpt4 book ai didi

node.js - Axios前端到Golang后端的CORS问题

转载 作者:行者123 更新时间:2023-12-01 22:24:22 24 4
gpt4 key购买 nike

目前对CORS失去了理智。我有一个使用Axios的Vue.js应用程序,将数据发布到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) {
...
}

这是经过数小时的工作搜索结果的结果。我大量引用了 this答案,并在使用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

我能找到的所有信息使我相信,目前我不应该看到此错误-我们将不胜感激。

最佳答案

最后通过将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)))

关于node.js - Axios前端到Golang后端的CORS问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60922194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com