当前位置: > > > > Axios前端到Golang后端CORS问题
Axios前端到Golang后端CORS问题
来源:stackoverflow
2024-04-21 13:21:36
0浏览
收藏
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《Axios前端到Golang后端CORS问题》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
目前我对 cors 失去了理智。我有一个 vue.js 应用程序,使用 axios 将数据发布到 golang 服务(使用 gorilla mux 和处理程序)。两个应用程序都在同一主机上运行。
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
我能找到的所有信息都让我相信我此时不应该看到此错误 – 任何帮助将不胜感激。
解决方案
最终通过将 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)))
到这里,我们也就讲完了《Axios前端到Golang后端CORS问题》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注米云公众号,带你了解更多关于的知识点!
