为什么我不能设置多个cookie

时间:2017-05-17 06:10:30

标签: openresty

我试图设置多个Cookie,但它不起作用:

if type(ngx.header["Set-Cookie"]) ~= "table" then
    ngx.header["Set-Cookie"] = {}
end
table.insert(ngx.header["Set-Cookie"], "Cookie1=abc; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie2=def; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie3=ghi; Path=/")

在客户端,我没有收到任何cookie。

2 个答案:

答案 0 :(得分:3)

ngx.header["Set-Cookie"]是一个特殊的表,每次修改时都必须用新表重新分配(插入或删除的元素对将发送给客户端的cookie没有影响):< / p>

if type(ngx.header["Set-Cookie"]) == "table" then
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", unpack(ngx.header["Set-Cookie"]) }
else
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", ngx.header["Set-Cookie"] }
end

答案 1 :(得分:1)

您可以使用https://github.com/cloudflare/lua-resty-cookie

local ck = require "resty.cookie"
local cookie, err = ck:new()
cookie:set({key = "Cookie1", value = "abc", path = "/"})
cookie:set({key = "Cookie2", value = "def", path = "/"})
cookie:set({key = "Cookie3", value = "ghi", path = "/"})