问题
I'm trying to use a cloudfare worker to add 2 cookie key/value pairs to the response before sending it to the client.
Unfortunately all documentation for the cloudflare workers says to use the response.headers.set('Set-Cookie',xxx) function to set the cookie value:
let response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Set-Cookie', "val1=x; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
return response;
This only allows you to set one cookie header, and if called twice just overwrites the existing header.
I have tried calling the function twice, only the last value comes in:
response.headers.set('Set-Cookie', "val1=1; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
response.headers.set('Set-Cookie', "val2=2; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
I have tried passing 2 cookies in the one header, separated with a comma, but only one comes in:
response.headers.set('Set-Cookie', "val1=1; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';, val2=2; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
I have tried passing 2 cookie key/value pairs, but the first key value is set to "1, val2=2":
response.headers.set('Set-Cookie', "val1=1, val2=2; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
None of these work.
The only work around I have found is to bundle the vars up into one variable, and then use JS on the client side to unpack and apply the variable:
response.headers.set('Set-Cookie', "jsVal={val1:1, val2:2}; Expires=Wed, 21 Oct 2020 07:28:00 GMT; Path='/';");
.. and then in a js file apply the 2 cookie values. Obviously this is not ideal.
Has anyone had any luck applying 2 separate cookies in one response header via a cloudflare worker? Thanks.
回答1:
There is Headers.append()
: https://developer.mozilla.org/en-US/docs/Web/API/Headers/append
The difference between set() and append() is that if the specified header already exists and accepts multiple values, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values.
来源:https://stackoverflow.com/questions/56844594/set-more-than-one-cookie-in-the-set-cookie-header-in-a-cloudflare-worker-heade