Next js 13.4 从 NodeJs API 获取 cookie

问题描述 投票:0回答:2

你们可以检查我的代码吗,我有一个 Nextjs 和 Node api 应用程序,并且我目前在将 cookie 从我的 api 获取到我的 Next 应用程序时遇到问题,我制作的signInUser api 应该返回生成的 jwt cookie,但是当我在我的下一个应用程序中使用它,它没有显示在我的开发工具应用程序cookies中,但是当尝试来自邮递员或雷霆客户端的api时,我在cookies选项卡中看到jwt令牌,我错过了什么?

这是我用于登录的后端 Node api 代码

const app = express();
app.use(cors());

 export const signInUser = async (
   req: express.Request,
   res: express.Response
   ) => {
  const { username, password } = req.body;

try {
let user = await getUserByEmail(username).select(
  "+authentication.password"
);

if (!user) {
  user = await getUserByUserName(username).select(
    "+authentication.password"
  );
}
if (!user) {
  const response: ResponseProps = {
    isError: true,
    message: "Invalid username or email",
  };
  res.status(400).json(response);
  return;
}
const passwordMatch = await bcrypt.compare(
  password,
  user.authentication.password
);

if (!passwordMatch) {
  const response: ResponseProps = {
    isError: true,
    message: "Invalid username/email or password",
  };
  res.status(400).json(response);
  return;
}
const response: ResponseProps = {
  isError: false,
  message: "Sign in successful",
  data: user,
};

这是我自定义的generateToken方法,它从signin api获取express.Response和user.Id

generateToken(res, user.id);
res.status(200).json(response);
 } catch (error) {
 res.status(400).json(error);
    }
 };

 export const generateToken = (res: express.Response, userId: String) => {
   const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
     expiresIn: "1d",
   });

   res.cookie("jwt", token, {
    httpOnly: true,
    secure: process.env.SERVER_ENVIRONMENT !== "development",
     sameSite: "strict",
    maxAge: 86400,
   });
  };

这是我的前端下一个登录代码

 const handleSignIn = async (values: z.infer<typeof formSchema>) => {
   setIsLoading(true);
   try {
    const res = await axios.post(SIGNIN_URL, values);
  const data = res.data;
  if (data.isError === true) {
    setSignInError("Invalid username or password.");
  } else {
    router.push("/home");
    form.reset();
    setSignInError("");
    toast({
      duration: 5000,
      variant: "default",
      title: "Success!",
      description: "Welcome back! What's up?",
    });
  }
  setIsLoading(false);
} catch (error) {
  toast({
    duration: 5000,
    variant: "destructive",
    title: "Uh oh! Something went wrong.",
    description: "There was a problem with your request.",
  });
  setIsLoading(false);
}

};

node.js reactjs next.js fetch-api next.js13
2个回答
0
投票

我唯一能想到的是

res.cookie
可能不会为不同的域设置cookie。 Postman 不强制执行同源策略,也不具有与浏览器相同的安全限制。
cors
是由浏览器实现的,这就是为什么我猜它可以在邮递员中工作。如果您使用选项在express中设置cors

import cors from "cors";

const options: cors.CorsOptions = {
  allowedHeaders: [
    "Origin",
    "X-Requested-With",
    "Content-Type",
    "Accept",
    "X-Access-Token",
  ],
  credentials: true,
  methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
  // whatever port for next.js
  origin: "http://localhost:3000",
  preflightContinue: true,
};
const app = express();

app.use(cors(options));

0
投票

像这样包含 withCredentials true const res =等待 axios.post(SIGNIN_URL, 值 ,{ withCredentials: true });

© www.soinside.com 2019 - 2024. All rights reserved.