在cloudflare worker标头的'Set-Cookie'标头中设置多个cookie.set('Set-Cookie'函数 [英] Set more than one cookie in the 'Set-Cookie' header in a cloudflare worker header.set('Set-Cookie' function

查看:297
本文介绍了在cloudflare worker标头的'Set-Cookie'标头中设置多个cookie.set('Set-Cookie'函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用cloudfare工作者将2个Cookie键/值对添加到响应中,然后再将其发送给客户端.

I'm trying to use a cloudfare worker to add 2 cookie key/value pairs to the response before sending it to the client.

不幸的是,所有关于cloudflare工作者的文档都说要使用response.headers.set('Set-Cookie',xxx)函数来设置cookie值:

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;

这仅允许您设置一个cookie标头,如果调用两次,将覆盖现有标头.

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='/';");

我尝试过在一个标头中传递2个cookie,并用逗号分隔,但只有一个进来:

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='/';");

我尝试传递2个cookie键/值对,但是第一个键值设置为"1,val2 = 2":

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='/';");

这些工作都没有.

我发现的唯一解决方法是将var捆绑为一个变量,然后在客户端使用JS来解压缩并应用变量:

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='/';");

..然后在js文件中应用2个cookie值.显然这是不理想的.

.. and then in a js file apply the 2 cookie values. Obviously this is not ideal.

有人通过cloudflare工作者在一个响应标头中应用2个单独的cookie的运气好吗?谢谢.

Has anyone had any luck applying 2 separate cookies in one response header via a cloudflare worker? Thanks.

推荐答案

Headers.append():

set()和append()之间的区别在于,如果指定了标头已经存在并接受多个值,set()将用新值覆盖现有值,而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.

这篇关于在cloudflare worker标头的'Set-Cookie'标头中设置多个cookie.set('Set-Cookie'函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆