【发布时间】:2020-07-10 07:53:17
【问题描述】:
目前正在对 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) {
...
}
这是对如何使其工作进行数小时搜索的结果。我大量引用了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
我能找到的所有信息都让我相信我现在不应该看到这个错误 - 任何帮助都将不胜感激。
【问题讨论】:
-
您希望方法仅为
POST和OPTIONS? -
是的,这是我目前正在实现的唯一功能。
标签: node.js vue.js go cors axios