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

标签 node.js vue.js go cors axios

目前对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/

相关文章:

node.js - i18n 不能使用本地化 url

eclipse - 如何在 eclipse 中获取 golang(go 语言)的调用层次结构/调用图/调用图?

在 Visual Studio Code 和 Delve 调试器中使用标签调试 Go

arrays - Goroutines 共享 slice : : trying to understand a data race

Vue.js 3 在运行时挂载组件实例

loops - 在 v-for 循环 vuejs 中插入命名槽

node.js - TypeORM:从订阅者中排除种子

javascript - 无法更新测验变量

node.js - promise nodejs + postgresql 中的错误句柄

vue.js - 为着陆/登录页面设置 Vue 路由器,然后使用导航作为后端