设置标头响应

发布于 2025-01-17 12:04:05 字数 1443 浏览 0 评论 0原文

我以前从未使用过cookie,目前尝试将数据存储在cookie中。这是我在console.log()

“

我想与setheader在header中设置cookie ()。这是用于将数据发送到后端的异步函数getJwt()。

async function getjwt(req, res) {
  const apiRes= await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/auth/jwt/create`,
    {
      method: "POST",
      headers: {
        Accept: "application/json",
        "content-Type": "application/json",
      },
      body: Body,
    }
  );
  console.log(apiRes);
  const data = await apiRes.json();
  console.log("+++++++++++++++++++++");
  console.log(data.access);
  console.log("+++++++++++++++++++++");
  if (apiRes.status === 200) {
    res.setHeader("Set-Cookie", [
      cookie.serialize("access", data.access, {
        httpOnly: true,
        secure: false,
        maxAge: 60 * 30,
        sameSite: "strict",
        path: "/auth/",
      }),
      cookie.serialize("refresh", data.refresh, {
        httpOnly: true,
        secure: false,
        maxAge: 60 * 60 * 24,
        sameSite: "strict",
        path: "/auth/",
      }),
    ]);
  } else {
    return res.status(apiRes.status).json({
      error: "Authentication failed",
    });
  }
}

错误 -

Uncaught (in promise) TypeError: res is undefined

如何将标题设置为响应。

I haven't work with cookies before and currently trying to store data in cookies.This is the response I am getting in console.log()

response in console.log()

I want to set cookies in header with setHeader(). This is the async function getjwt() using to send data to backend.

async function getjwt(req, res) {
  const apiRes= await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/auth/jwt/create`,
    {
      method: "POST",
      headers: {
        Accept: "application/json",
        "content-Type": "application/json",
      },
      body: Body,
    }
  );
  console.log(apiRes);
  const data = await apiRes.json();
  console.log("+++++++++++++++++++++");
  console.log(data.access);
  console.log("+++++++++++++++++++++");
  if (apiRes.status === 200) {
    res.setHeader("Set-Cookie", [
      cookie.serialize("access", data.access, {
        httpOnly: true,
        secure: false,
        maxAge: 60 * 30,
        sameSite: "strict",
        path: "/auth/",
      }),
      cookie.serialize("refresh", data.refresh, {
        httpOnly: true,
        secure: false,
        maxAge: 60 * 60 * 24,
        sameSite: "strict",
        path: "/auth/",
      }),
    ]);
  } else {
    return res.status(apiRes.status).json({
      error: "Authentication failed",
    });
  }
}

ERROR-

Uncaught (in promise) TypeError: res is undefined

how can I set Header in response.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文