Remix会话值不会跨页面保持。

huangapple go评论54阅读模式
英文:

Remix session values don't persist across pages

问题

我正在使用Remix创建一个网站,我想要在不同页面之间持久化会话值。我认为问题出在getSession请求上,因为这些值在对同一页面的多次请求之间不会持久化。我在sessions.ts中实现了一个会话Cookie:

const { getSession, commitSession, destroySession } =
    createCookieSessionStorage<SessionData, SessionFlashData>(
        {
            // 创建Cookie的选项
            cookie: {
                name: "__session",
                maxAge: 1200,
                path: "/",
                sameSite: "none",
                secure: true,
                secrets: ["surprise"]
            },
        }
    );

在一个页面上,我设置了一个值并将其记录下来,并获得了预期的值:

export const loader = async ({ request }: LoaderArgs) => {
    const session = await getSession(
        request.headers.get("Cookie")
    );
    session.set("token", "abc123")
    var data = { "count": 2 }
    console.log(session.get("token"))
    return json(data, {
        headers: {
            "Set-Cookie": await commitSession(session),
        },
    });
};

然而,当我尝试在另一个页面访问该值时,该值为undefined:

export const loader = async ({ request }: LoaderArgs) => {
  const session = await getSession(
    request.headers.get("Cookie")
  );
  var data = { "abc": 442 }
  console.log(session.get("token"))
  return json(data, {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });

  return null
};

我对Remix和React非常新,请帮助我解决问题,谢谢!

英文:

I'm making a site using Remix where I'd like to persist session values across pages. I think the issue lies in the getSession request, as the values do not persist across requests to the same page. I have implemented a session cookie in sessions.ts:

const { getSession, commitSession, destroySession } =
    createCookieSessionStorage&lt;SessionData, SessionFlashData&gt;(
        {
            //cookie options to create a cookie
            cookie: {
                name: &quot;__session&quot;,
                maxAge: 1200,
                path: &quot;/&quot;,
                sameSite: &quot;none&quot;,
                secure: true,
                secrets: [&quot;surprise&quot;]

            },
        }
    );

On one page I set a value and log it out and receive the expected value

export const loader = async ({ request }: LoaderArgs) =&gt; {
    const session = await getSession(
        request.headers.get(&quot;Cookie&quot;)
    );
    session.set(&quot;token&quot;, &quot;abc123&quot;)
    var data = { &quot;count&quot;: 2 }
    console.log(session.get(&quot;token&quot;))
    return json(data, {
        headers: {
            &quot;Set-Cookie&quot;: await commitSession(session),
        },
    });
};

however when i try to access the value in a different page, the value is undefined

export const loader = async ({ request }: LoaderArgs) =&gt; {
  const session = await getSession(
    request.headers.get(&quot;Cookie&quot;)
  );
  var data = { &quot;abc&quot;: 442 }
  console.log(session.get(&quot;token&quot;))
  return json(data, {
    headers: {
      &quot;Set-Cookie&quot;: await commitSession(session),
    },
  });

  return null


};

I'm very new to remix and react so appreciate any help!

答案1

得分: 0

eht eussi saw ot od htiw eht emitSemas noitpo dna ecurS snoitpo.
sa I ma gnikrow ylcol, ecruS tsum eb tes ot eslaf hcihw snaem emitSemas tsu tsum eb rehtie xal ro tsirts

英文:

the issue was to do with the sameSite option and Secure options.
as I am working locally, Secure must be set to false which means sameSite must be either lax or strict

答案2

得分: 0

@Ov_.01的回答是正确的。我不得不将我的secureprocess.env.NODE_ENV === &#39;production&#39;更改为明确的false。这是我完整的Cookie,允许会话在本地持续存在。

const sessionStorage = createCookieSessionStorage({
  cookie: {
    // secure: process.env.NODE_ENV === &#39;production&#39;,
    secure: false, // TODO: 在使用process.env.NODE_ENV === &#39;production&#39;时本地会话不会持续存在
    secrets: [process.env.SESSION_SECRET],
    sameSite: &#39;lax&#39;,
    maxAge: 30 * 24 * 60 * 60, // 30天
    httpOnly: true
  }
})
英文:

Answer from @Ov_.01 is correct. I had to change my secure from process.env.NODE_ENV === &#39;production&#39; to an explicit false. This was my full cookie that allowed sessions to persist for me locally.

const sessionStorage = createCookieSessionStorage({
  cookie: {
    // secure: process.env.NODE_ENV === &#39;production&#39;,
    secure: false, // TODO: local session doesn&#39;t persist when using process.env.NODE_ENV === &#39;production&#39;
    secrets: [process.env.SESSION_SECRET],
    sameSite: &#39;lax&#39;,
    maxAge: 30 * 24 * 60 * 60, // 30 days
    httpOnly: true
  }
})

huangapple
  • 本文由 发表于 2023年6月2日 03:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定