我有一个 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 相关的内容,还是在客户端进行了错误的身份验证。有什么帮助吗?谢谢。
潇湘沐
沧海一幻觉
慕姐8265434
随时随地看视频慕课网APP
相关分类