英文:
Can't get the cookies from golang server inside the react js project
问题
我有一个用Golang编写的简单服务器,它应该处理登录请求并设置一些cookie。
但问题是我无法在我的React Js项目中访问这些cookie。
我使用以下代码设置cookie:
if OTPValidate.Result.Status == "success" {
log.Println("Setting Cookies")
session := sessions.DefaultMany(ginContext, "session")
session.Set("MobileNumber", Number)
session.Set("GUID", OTPValidate.GUID)
session.Set("PersonId", OTPValidate.PersonID)
if err != nil {
logger.Error(logger.FuncName() + err.Error())
}
session.Options(sessions.Options{MaxAge: 2592000}) // 30 Day
session.Save()
}
我目前使用Cookies Js来获取cookie:
const cookie = Cookies.get('session')
console.log(cookie)
但它打印出undefined。
我在浏览器的网络选项卡中检查了请求头,看起来没问题。
但是我仍然无法在React中获取它们。
英文:
I have a simple server written on Golang and it's supposed to handle login requests and set some cookies.
But the problem is that i cant access the cookies inside my React Js project
I set the cookies with this code:
if OTPValidate.Result.Status == "success" {
log.Println("Setting Cookies")
session := sessions.DefaultMany(ginContext, "session")
session.Set("MobileNumber", Number)
session.Set("GUID", OTPValidate.GUID)
session.Set("PersonId", OTPValidate.PersonID)
if err != nil {
logger.Error(logger.FuncName() + err.Error())
}
session.Options(sessions.Options{MaxAge: 2592000}) // 30 Day
session.Save()
}
and currently using Cookies Js to get the cookies:
const cookie = Cookies.get('session')
console.log(cookie)
but it prints undefined
I checked the request header inside the network tab in the browser and it seems fine:
But still I'm not able to get them into the react
答案1
得分: 1
提供JS访问授权cookie是不可接受的,这将导致严重的安全事件,使用户无法访问其账户:https://en.wikipedia.org/wiki/Secure_cookie。
但是,如果你仍然想这样做,就像Osman在评论中所说,你需要确保正确设置cookie:
http.SetCookie(w, &http.Cookie{
Name: `session`,
Value: url.QueryEscape(sid),
Expires: time.Now().Add(time.Hour),
Path: "/",
Secure: false, // Secure = false 允许从js访问
HttpOnly: true,
SameSite: http.SameSiteNoneMode,
})
英文:
It is unacceptable to provide access from JS to authorization cookies, this will lead you to serious incidents with the loss of user access to their accounts: https://en.wikipedia.org/wiki/Secure_cookie.
But if you still want do it, as Osman said in comments, you need to be sure you set cookie right way:
http.SetCookie(w, &http.Cookie{
Name: `session`,
Value: url.QueryEscape(sid),
Expires: time.Now().Add(time.Hour),
Path: "/",
Secure: false, // Secure = false allow to access from js
HttpOnly: true,
SameSite: http.SameSiteNoneMode,
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论