javascript node.js 请求中的多个“Cookie”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18456098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:00:07  来源:igfitidea点击:

Multiple 'Cookie' headers in a node.js request

javascriptnode.jscookieshttp-headersrequest

提问by twinlakes

I've seen how to make a request with a single cookie, and I've seen how to write a response with multiple cookies, but does anyone know how to write a request in node.js using http module (if possible) with multiple 'Cookie' headers?

我已经看到如何使用单个 cookie 发出请求,并且我已经看到如何使用多个 cookie 编写响应,但是有没有人知道如何使用具有多个的 http 模块(如果可能)在 node.js 中编写请求'Cookie' 标题?

So far the only ways I've seen to make a request in node.js involve passing an object as the parameter to a function, which would require having two identical keys.

到目前为止,我所见过的在 node.js 中发出请求的唯一方法涉及将对象作为参数传递给函数,这需要有两个相同的键。

headers = {
    Cookie: firstCookie,
    Cookie: secondCookie
}

so wouldn't work.

所以不会工作。

This is a node.js question, but I'm not extremely confident with http, so I'm not sure if there isn't a way to set two distinct cookies in header. Is it possible to concatenate the two into a single header? Would a request with two separately defined cookies vary from one with a single header containing both?

这是一个 node.js 问题,但我对 http 不是很有信心,所以我不确定是否没有办法在标头中设置两个不同的 cookie。是否可以将两者连接成一个标题?具有两个单独定义的 cookie 的请求会与一个包含两者的单个标头的请求不同吗?

回答by ranm8

The 'Cookie' property you added is a direct header in your HTTP request. You should use only one 'Cookie' header and encode your cookies properly to one valid cookie header string, like that:

您添加的“Cookie”属性是 HTTP 请求中的直接标头。您应该只使用一个“Cookie”标头并将您的 cookie 正确编码为一个有效的 cookie 标头字符串,如下所示:

var headers = {
    Cookie: 'key1=value1; key2=value2'
}

Also, instead of using nodeJS native HTTP client which usually will make you write lots of boilerplate code, I would recommend you to use a much simplified library like Requestify..

此外,我建议您不要使用通常会让您编写大量样板代码的 nodeJS 原生 HTTP 客户端,而是建议您使用一个非常简单的库,例如Requestify..

This is how you can make an HTTP request with cookies using requestify:

这是使用 requestify 使用 cookie 发出 HTTP 请求的方法:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource', {
    cookies: {
        'key1': 'val1',
        'key2': 'val2',    
    }
})
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);