golang 服务器上的 CORS 和 javascript 获取前端

我有一个 golang HTTP 服务器,其代码如下:


    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {

    log.Println("New incoming request")


    // Authenticate

    if u, p, ok := r.BasicAuth(); ok {

      log.Println("Success")

      return

    }

    log.Println("Failed")

我从一个 JS 前端调用这个 HTTP 端点,这是一个部署在端口 3000 上的反应应用程序,使用代码:


      fetch('http://localhost:8080/login', {

            method: 'post',

            headers: {

                'Authorization': 'Basic ' + btoa(authHeader),

                'Content-Type': 'application/x-www-form-urlencoded',

                'Access-Control-Allow-Origin': '*'

            },

                body: 'A=1&B=2'

            })

            .then(function (response) {

                console.log("Authentication Success")

            })

            .catch(function (err) {

                console.log("Authentication fail", err)

            });

上面的代码失败并显示以下日志。


在服务器端:


New incoming request

Failed

在浏览器上,在开发者工具日志中:


Fetch API cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

有人可以帮助解决身份验证问题吗?我不确定我是在服务器端遗漏了与 CORS 相关的内容,还是在客户端进行了错误的身份验证。有什么帮助吗?谢谢。


潇湘沐
浏览 204回答 2
2回答

沧海一幻觉

Access-Control-Allow-Origin: *必须从服务器发送,而不是由客户端发送。假设您在标准net/http处理程序函数中,请尝试以下代码:func handler(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Access-Control-Allow-Origin", "*")    if (r.Method == "OPTIONS") {        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed    } else {        // Your code goes here    }}

慕姐8265434

首先 - 您需要在处理程序中使用模式:w.Header().Set("Access-Control-Allow-Origin", "*")    if (r.Method == "OPTIONS") {        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed    } else {        // Your code goes here    }但在此之前,您需要在主“选项”中指定:router.HandleFunc("/your_route/", your_method).Methods("POST", "OPTIONS")这是因为您的浏览器执行 2 个请求 - 首先检查使用某些标头的能力(例如授权),下一步是发布数据
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go