如何在NextJS 14中的客户端浏览器中设置cookie?

ccgok5k5  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(262)

我尝试在客户端浏览器中使用API文件夹中的nextjs 14应用路由器保存cookie,但不起作用

这里是代码
app/API/auth/login/route.js

const { NextResponse } = require("next/server");
import connect from "@/app/lib/mongodb";
import MemberModel from "@/app/models/Member.model";
import Notifications from "@/app/models/Notifications";
import { cookies } from "next/headers";
const CryptoJS = require("crypto-js");

export async function POST(req) {
    const data = await req.json()
    await connect()
    let userdata = await MemberModel.find({
        email: data.email
    })
    if (userdata.length === 0) {
        return NextResponse.json({ uid: false })
    }
    if ((userdata[0].email === data.email) && ((CryptoJS.AES.decrypt(userdata[0].password, process.env.CRYPTO_SECRET_KEY).toString(CryptoJS.enc.Utf8)) === data.password)) {
        const oneDay = 24 * 60 * 60 * 1000
        cookies().set('email', (CryptoJS.AES.decrypt(userdata[0].password, process.env.CRYPTO_SECRET_KEY).toString(CryptoJS.enc.Utf8)), { expires: Date.now() + oneDay })
        await Notifications.create({
            msg: `User login with email : ${userdata[0].email}`
        })
        return NextResponse.json({ uid: true })
    } else {
        return NextResponse.json({ uid: false })
    }
}

字符串

nwwlzxa7

nwwlzxa71#

预期输出:

在客户端设置cookie

原因:

您的响应不包含Set-Cookie标头

解决方案:

更改您的代码:

return NextResponse.json({ uid: true })

字符串

return NextResponse.json(
    { uid: true },
    { headers: { 'Set-Cookie': `COOKIE_VALUE` } },
);

如果你还有任何疑问,请留下评论。

相关问题