【问题标题】:How to get session in NextJS api route using with-iron-session?如何使用 with-iron-session 在 NextJS api 路由中获取会话?
【发布时间】:2021-11-02 15:29:46
【问题描述】:

我在我的 NextJS 应用程序中使用 with-iron-session 进行身份验证,但是当我在 getServerSideProps() 函数中进行 API 调用时,我无法访问会话 cookie。 API 路由无法获取用于认证的会话 cookie:

会话创建:

// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import { withIronSession } from "next-iron-session";

export default function withSession(handler) {
  return withIronSession(handler, {
    password: process.env.PASSWORD_HASH,
    cookieName: "MYCOOKIE",
    cookieOptions: {
      // the next line allows to use the session in non-https environements like
      // Next.js dev mode (http://localhost:3000)
      secure: process.env.NODE_ENV === "production",
      httpOnly: false,
    },
  });
}

我的 getServerSideProps 调用:

export const getServerSideProps = withSession(async ({ req, res }) => {
  const user = req.session.get("user");

  if (!user) {
    return {
      redirect: {
        permanent: false,
        destination: "/"
      },
      props: {}
    };
  }
  // I've replaced 'include' with 'same-origin' but it didn't make a difference
  const watchRes = await fetch('/watch',{credentials: 'include'});
  const watch = await watchRes.json();

  return{
    props: {
      user,
      watch
    }
  }
}

api 路由:

// I've added await before the (req,res) but that was just guessing at this point
export default withSession((req, res) => {
    const user = req.session.get("user");
    if(user){
    
       res.send("Good");
    }else{
       res.status(403).end();
    }
}

当我登录并转到我的localhost/api/watch 路由时,它显示“良好”,但当我尝试获取请求时,我得到了 403。

【问题讨论】:

  • 请记住,getServerSideProps 在服务器端运行(就像 API 路由一样),因此与其调用内部 API,不如直接在 getServerSideProps 中使用 API 路由中的逻辑。

标签: reactjs next.js


【解决方案1】:

尝试将 getServerSideProps 请求的标头 添加到第二次调用。

const headers = req.headers
const watchRes = await fetch('/watch',{headers});

这样你就注入了cookies

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2022-10-24
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多