如何设置 cookie 然后使用本机 http/https 模块重定向?

How can I set a cookie then redirect using the native http/https modules?

我只能找到使用 express 执行此操作的示例。我尝试了几件事,包括这个:

res.writeHead(200, {
    'Set-Cookie': cookie,
    'Content-Type': 'text/plain'
})
res.writeHead(302, {'Location': '/'})
res.end()

如果我不尝试重定向,则 cookie 会正常设置,但客户端会留下一个空白页面。如果我尝试重定向,则未设置 cookie。我还尝试使用 HTML 重定向的 HTML 页面进行响应,但未设置 cookie。只有当我除了设置 cookie 什么都不做时,cookie 才会设置。但是随后用户留下一个空白页面,必须手动按下刷新页面按钮才能看到任何内容。

编辑:如果需要任何其他信息来帮助我,请告诉我。

解决方案是对 cookie 使用 setHeader 而不是 writeHead:

res.setHeader('Set-Cookie', cookie)
res.writeHead(302, {'Location': '/'})
res.end()