无法使用 NextJS 9 的 API 路由设置 cookie [英] Can't set a cookie using NextJS 9's API Route

查看:37
本文介绍了无法使用 NextJS 9 的 API 路由设置 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在使用 Express 时,res"对象中有cookie",因此您可以执行以下操作:

Typically it seems that when using Express, in the "res" object there is "cookie" so you can do something like:

res.cookie('session', sessionCookie, options);

在 Next 9 中 NextJS 提供的 API 路由中,查看 res 时,这是不存在的.有没有办法在 Next API Route 函数中为响应对象设置 cookie?

In the API routes offered by NextJS in Next 9, when looking at res, this does not exist. Is there a way to set the cookie for a response object in a Next API Route function?

推荐答案

改编自官方repo中间件example,你可以通过 res 设置 Set-Cookie 标头,如下所示:

Adapted from offical repo middleware example, you can set Set-Cookie header via res like so:

import { serialize } from 'cookie';

function (req, res) {
   // ...
   // setHeader(headerName: string, cookies: string | string[])
   // can use array for multiple cookies
   res.setHeader('Set-Cookie', serialize('token', 'token_cookie_value', { path: '/' }));
}

这篇关于无法使用 NextJS 9 的 API 路由设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆