在 Next.js api 文件夹中使用 noookies 设置 cookie

Joh*_*ohn 5 javascript node.js next.js

我正在尝试使用 Next.js api 文件夹使用 npm 包设置 cookie nookies。我已经使用了类似的代码来设置 cookie,并且nookies效果很好。由于某种原因,它在这种情况下不起作用。我不确定我做错了什么。如果您有任何想法,请告诉我。

import { parseCookies, setCookie } from 'nookies';
import { paymentIntent } from '@/Models/Stripe';
import { cartByUser } from '@/Models/Cart';
import { currentUser } from '@/Models/User';

export const createPaymentIntentController = async (req, res) => {
  const { email } = req.user;
  const { couponApplied } = req.body;

  const { appPaymentIntentId } = parseCookies({req});
  console.log({ appPaymentIntentId });

  try {
    const user = await currentUser(email);
    const cart = await cartByUser(user._id);
    const result = await paymentIntent(cart, couponApplied, appPaymentIntentId);

    if (!appPaymentIntentId) {
      console.log('result.paymentIntent.id: ', result.paymentIntent.id); // pi_1JFc5jJM2kZsXGkUm18Z8B2J typeof string

      setCookie({ res }, 'appPaymentIntentId', result.paymentIntent.id, {
        // maxAge: 72576000,
        httpOnly: true,
        path: '/',
      });
    }

    res.send(result);
  } catch (error) {
    console.log(`createPaymentIntentController error: ${error}`);
  }
};
Run Code Online (Sandbox Code Playgroud)

小智 0

你应该使用

nookies.set(
  {res}, 
  'appPaymentIntentId',
  result.paymentIntent.id, 
  { httpOnly: true, path: '/' }
)
Run Code Online (Sandbox Code Playgroud)

设置服务器端cookie