【问题标题】:Axios frontend to Golang backend CORS problemsAxios 前端到 Golang 后端 CORS 问题
【发布时间】: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

我能找到的所有信息都让我相信我现在不应该看到这个错误 - 任何帮助都将不胜感激。

【问题讨论】:

  • 您希望方法仅为POSTOPTIONS
  • 是的,这是我目前正在实现的唯一功能。

标签: node.js vue.js go cors axios


【解决方案1】:

最后通过将 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-06-30
    • 2020-12-04
    • 2018-06-12
    • 2019-09-24
    • 2021-09-04
    • 2020-11-07
    • 2021-10-24
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多