【发布时间】:2021-04-09 20:48:19
【问题描述】:
我正在尝试从 Go (127.0.0.1:8080) 制作的 API 在我的客户端 (127.0.0.1:3000) 中创建一个 cookie,我想我已经在 CORS 和cookie 具有 samesite=none 和 secure=true 但仍未设置。下面我添加了请求和响应的图片,如 chrome devtools 网络选项卡中所示,以及发出请求的 axios 代码和 API 服务器中处理请求的 go 代码。
开始:
//Handles account sign ins
func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Println("login handler")
//decoder := json.NewDecoder(r.Body)
//var t models.LoginUserData
//err := decoder.Decode(&t)
//if err != nil {
// log.Println(err)
//}
//middleware.SignIn(t.User.Username, t.User.Password)
http.SetCookie(w, &http.Cookie{Name: "sabor", Value: "merda", Path: "/", HttpOnly: false, SameSite: http.SameSiteNoneMode, Secure: true, Domain: "127.0.0.1"})
header := w.Header()
header.Set("Access-Control-Allow-Credentials", "true")
//header.Set("Access-Control-Expose-Headers", "Set-Cookie")
header.Set("Access-Control-Allow-Headers", "Content-Type, withCredentials")
header.Set("Access-Control-Allow-Origin", "http://127.0.0.1:3000")
header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.WriteHeader(http.StatusOK)
}
Axios:
let config = {
headers: {
withCredentials: true,
},
};
axios
.post(
"http://127.0.0.1:8080/login",
{
User: {
Username: username,
Password: password,
},
},
config
)
.then(function (response) {
console.log(response)
console.log(response.data)
console.log(response.headers)
console.log(response.data.cookie)
if (response.status === 200) {
console.log("if works")
}
})
.catch(function (error) {
console.log(error);
});
请求和响应图片: Request and response image
【问题讨论】:
-
IP 地址上的域 Cookie 是一件困难的事情,因为对于这是否有意义以及如何处理它们没有达成共识。请注意,端口不会在 cookie 身份中发挥作用,因此此处不应发生 CORS 问题。你为什么要为环回地址创建一个 domain cookie?这是非常荒谬的。
-
@Volker 那我应该如何创建 cookie?如果我不在响应中包含这些标头,我将在浏览器的控制台上收到 CORS 错误。
-
我不是在谈论 CORS,我是在谈论 cookie 作为域 cookie。不要被 CORS 所牵制。
-
@Volker 哦,我在域字段不起作用之后添加了域字段,我不知道还要尝试什么,但它没有改变任何东西,我现在可以删除它,我仍然会得到相同的结果。我没有特别的理由这样做。你能帮我弄清楚是什么阻止了cookie被设置吗?
-
不,我帮不了你,但我知道将 cookie 设置为 IP 地址的域 cookie 并没有帮助。
标签: http go cookies axios cross-domain