Golang中非localhost域名无法设置Cookie的问题

Golang中非localhost域名无法设置Cookie的问题 我在使用 Gin Gonic 设置非 localhost 的 Cookie 时遇到了问题。

c.SetCookie("token", str, 60*60*24, "/", "localhost:3000", true, true) // 有效

c.SetCookie("token", str, 60*60*24, "/", "192.162.1.12:3000", true, true) // 无效

我的请求头配置如下:

router.Use(cors.New(cors.Config{
	AllowOrigins:     []string{"http://localhost:3000", "http://192.168.1.10:3000"},
	AllowMethods:     []string{"POST", "OPTIONS", "GET", "PUT", "DELETE"},
	AllowHeaders:     []string{"Accept", "Authorization", "Content-Type", "Content-Length", "X-CSRF-Token", "Token", "session", "Origin", "Host", "Connection", "Accept-Encoding", "Accept-Language", "X-Requested-With"},
	ExposeHeaders:    []string{"Content-Length"},
	AllowCredentials: true,
	// AllowOriginFunc: func(origin string) bool {
	// 	return origin == "https://github.com"
	// },
	MaxAge: 24 * time.Hour,
}))

我是从本地 React 页面 http://192.162.1.12:3000 调用该 API 的。


更多关于Golang中非localhost域名无法设置Cookie的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

通过添加以下代码解决:

c.SetCookie(“token”, str, 60*60*24, “/”, “http://localhost”, true, true)
c.SetCookie(“token”, str, 60*60*24, “/”, “http://192.162.1.12”, true, true)

更多关于Golang中非localhost域名无法设置Cookie的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题在于Cookie的Domain设置。对于IP地址,不应该在SetCookie的domain参数中指定端口号,且需要确保SameSite设置正确。

// 对于IP地址,domain参数应该只包含IP,不要包含端口
c.SetCookie("token", str, 60*60*24, "/", "192.168.1.12", true, true)

// 或者更好的做法是使用空字符串,让浏览器自动处理
c.SetCookie("token", str, 60*60*24, "/", "", true, true)

同时,需要调整CORS配置,确保正确处理凭据:

router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"http://localhost:3000", "http://192.168.1.12:3000"},
    AllowMethods:     []string{"POST", "OPTIONS", "GET", "PUT", "DELETE"},
    AllowHeaders:     []string{"Accept", "Authorization", "Content-Type", "Content-Length", "X-CSRF-Token", "Token", "session", "Origin", "Host", "Connection", "Accept-Encoding", "Accept-Language", "X-Requested-With"},
    ExposeHeaders:    []string{"Content-Length", "Set-Cookie"},
    AllowCredentials: true,
    MaxAge: 24 * time.Hour,
}))

在React端,需要确保fetch请求包含凭据:

fetch('http://your-api-address:port/endpoint', {
    method: 'GET',
    credentials: 'include', // 重要:包含Cookie
    headers: {
        'Content-Type': 'application/json',
    },
})

如果问题仍然存在,可以尝试设置SameSite属性为None:

// 创建自定义的Cookie设置
http.SetCookie(c.Writer, &http.Cookie{
    Name:     "token",
    Value:    str,
    Path:     "/",
    Domain:   "192.168.1.12",
    MaxAge:   60 * 60 * 24,
    Secure:   true,
    HttpOnly: true,
    SameSite: http.SameSiteNoneMode,
})
回到顶部