卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

浏览器未保存cookie

浏览器未保存cookie

php小编柚子在这里为大家介绍一个常见的问题——浏览器未保存cookie。在我们日常使用浏览器进行网页访问时,cookie是一种常见的机制,它可以帮助网站记住用户的登录状态、个性化设置等信息。然而,有时候我们会遇到浏览器未保存cookie的情况,导致登录状态丢失、无法正常浏览网页等问题。那么,为什么会出现这种情况呢?下面就让我们一起来探究一下吧!

问题内容

尝试了 15648070,15648070 不幸的是没有成功:)

您好,第一次使用 gin 构建 api,我在浏览器上设置 cookie 时遇到一些问题

我的意思是,当在 dev 工具 上查看请求时,我看到了 set-cookie 标头和正确的值,也在该请求中的 cookie 选项卡下我还看到了 cookie

主要问题是它没有保存在我的浏览器上(dev工具 -> application -> storage -> cookies和我的cookie不存在)

后端:

router.use(cors.new(cors.config{
        allowmethods:     []string{"get", "post", "put", "patch", "delete", "head", "options"},
        allowheaders:     []string{"origin", "content-length", "content-type"},
        maxage:           12 * time.hour,
        allowallorigins:  true,
        allowcredentials: true,
    }))

    router.post("/users/login", server.loginuser)
func (server *server) loginuser(ctx *gin.context) {
        ...
    ctx.setcookie("access_token", accesstoken, 3600, "/", "localhost", false, true)
    ctx.setcookie("refresh_token", refreshtoken, 3600, "/", "localhost", false, true)

    ctx.json(http.statusok, gin.h{"ok": true, "payload": rsps})

}

前端:

const login = async () => {
    const res = await fetch("http://localhost:3000/users/login", {
      method: "POST",
      body: JSON.stringify({ username, password }),
    });
    const data = await res.json();
    console.log(data);
  };
  const handleFormSubmit = (e) => {
    e.preventDefault();
    login();
  };

  return (
    
      <h1>Login Page</h1>
      <form onSubmit={handleFormSubmit}>
         ...
        <button type="submit">Login</button>
      </form>
    
  );

任何线索..?

解决方法

(感谢 Discord 上的 #Reactiflux 频道)

我错过了两件事..

服务器端:

  • AllowHeaders headers -> 添加 "Access-Control-Allow-Headers", "Authorization"

  • 添加 AllowOriginFunc -> 意味着不允许 * 而不是特定域

前端:

  • withCredentials: true 添加到我的 axios 配置
卓越飞翔博客
上一篇: 使用带有sync.WaitGroup的goroutine结果不一致
下一篇: 无法从其他容器连接到数据库 Postgres Docker 容器
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏