【问题标题】:How set multiple cookies with res.cookie(key , value) on NodeJS?如何在 NodeJS 上使用 res.cookie(key , value) 设置多个 cookie?
【发布时间】:2020-09-24 06:58:22
【问题描述】:

我正在使用 NodeJS 上的 cookie,我想知道如何设置多个 cookie 以在客户端发送。

我试过了:

1-

     var headers = {
      Cookie: 'key1=value1; key2=value2'
  }
  res.cookie(headers)

2-

res.cookie("isStillHere" , 'yes it is !').send('Cookie is set');
res.cookie("IP" , ip).send('Cookie is set');

3-

  var setMultipleCookies =  []
 setMultipleCookies.push('key1=value1','key2=value2')
  res.cookie(setMultipleCookies)

似乎没有任何作用。出了什么问题?任何提示都会很棒,

谢谢

【问题讨论】:

  • 你在使用Connect/Express框架吗?
  • @m1ch4is 是的,我正在使用 Express

标签: javascript node.js cookies


【解决方案1】:

您只需多次调用cookie而不在它们之间调用send。仅在完成所有 cookie 后才调用 send,因为 send 发送响应正文,并且 cookie 标头...嗯...在标头中。 :-)

res.cookie("isStillHere" , 'yes it is !');
res.cookie("IP" , ip);
res.send('Cookie is set');

【讨论】:

    【解决方案2】:

    您必须在拨打res.send()之前设置所有cookies

    res.cookie("isStillHere" , 'yes it is !');
    res.cookie("IP" , ip);
    res.send('Cookie is set');
    

    【讨论】:

      【解决方案3】:

      ShortHand(不是那么短),通过管道传递函数。

      res.cookie('cookie1' : { name: 'Leo' }).cookie('cookie2' : 'Teste').send()
      

      【讨论】:

        猜你喜欢
        • 2021-11-21
        • 2019-05-16
        • 2019-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 2013-11-01
        相关资源
        最近更新 更多