为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
潇湘沐 2022-04-20 16:59:44
我有一个 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 requestFailed在浏览器上,在开发者工具日志中: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 相关的内容,还是在客户端进行了错误的身份验证。有什么帮助吗?谢谢。
查看完整描述

2 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

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

    }

}


查看完整回答
反对 回复 2022-04-20
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

首先 - 您需要在处理程序中使用模式:


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 个请求 - 首先检查使用某些标头的能力(例如授权),下一步是发布数据


查看完整回答
反对 回复 2022-04-20
  • 2 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号