问题
I'm trying to set multiple cookies, but it's not working:
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=/")
On the client I do not receive any cookies.
回答1:
ngx.header["Set-Cookie"]
is a special table, and must be reassigned to with a new table every time you modify it (elements inserted or removed from it have no effect on the cookies that will be sent to the client):
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
回答2:
You can use 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 = "/"})
来源:https://stackoverflow.com/questions/44016867/how-come-i-cannot-set-multiple-cookies