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

查看:478
本文介绍了无法使用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?

推荐答案

从官方回购中间件

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

import { serialize } from 'cookie';

function (req, res) {
   // ...
   res.setHeader('Set-Cookie', serialize('token', 'token_cookie_value', { path: '/' }));
}

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

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