【问题标题】:Can't set a cookie using NextJS 9's API Route无法使用 NextJS 9 的 API 路由设置 cookie
【发布时间】:2019-12-24 19:42:07
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript node.js next.js


    【解决方案1】:

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

    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: '/' }));
    }
    

    【讨论】:

    • 多个 cookie 怎么样?多次这样做是否有效?
    • @Afsanefda,您可以像这样在第二个参数中使用数组:res.setHeader('Set-Cookie', [ serialize('foo', 'bar', { path: '/' }), serialize('hello', 'world', { path: '/' }) ]);
    • hint,如果你使用 typescript,你应该安装类型定义作为开发依赖:npm i -D @types/cookie
    • 你也可以设置 HttpOnly cookie 和 serialize('token', token, { httpOnly: true }) github.com/jshttp/cookie/blob/master/index.js#L91
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多