gpt4 book ai didi

javascript - golang api 请求在浏览器中有效,但在从本地运行的 JavaScript 请求时返回 401(未经授权)

转载 作者:IT王子 更新时间:2023-10-29 02:02:33 24 4
gpt4 key购买 nike

我有一个使用 golang 构建的 RESTful api 在端口 3000 上运行

当我在浏览器中导航到 http://localhost:3000 时,我得到了 200(成功)。服务器还成功向我发送了带有服务器 cookie 值的 JSON。

但是,当我尝试从正在端口 8080 上运行的 JavaScript SPA 中Fetch 代码时,我得到了 401(未授权) 响应。我还收到描述 http: named cookie not present 的服务器错误。

我包含了一个非常精简的版本:

myapp.js

fetch("http://localhost:3000/authenticate")
.then((r) => {
return r;
})
.then((r) => {
console.log(r)
})

server.go

package main

// func respond(w http.ResponseWriter, value *string, status int)
// writes header and encoded json

func main() {
http.HandleFunc("/authenticate", func(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie("cookie_name")
if err != nil {
// here's where I get the server error
fmt.Println(err)
respond(w, nil, http.StatusTeapot)
return
}
respond(w, cookie.Value, http.StatusOK)
})
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:8080"},
AllowCredentials: true,
})
handler := c.Handler(mux)
http.ListenAndServe(":3000", handler)
}

我很确定这不是 CORS 问题。在示例中,出于演示目的,我刚刚给出的错误是 418 (I'm a teapot)。真正的问题似乎在于服务器错误提示 http: named cookie not present,即使当我查看位于 http://localhost:3000 的 cookie 时也是如此浏览器就在那里。

我的 JavaScript SPA 正在 webpack-dev-server 端口 8080 上运行,所以这可能是问题的根源?也就是说,我真的很想能够使用 webpack 在本地测试我的应用程序。

为什么从 JavaScript 请求时服务器无法读取 cookie?

最佳答案

您不能拥有跨域 cookie。

在您的例子中,cookie 存储在浏览器端,用于站点 localhost:8080。但是,当访问 localhost:3000 时它不可用。

解决方案是使用同一台服务器为您的网站提供服务,或者使用 GET 或 POST 参数。

关于javascript - golang api 请求在浏览器中有效,但在从本地运行的 JavaScript 请求时返回 401(未经授权),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47217014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com