如何从 node.js 中的请求模块获取 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34218141/
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
How to get cookies from request module in node.js?
提问by Juntae
function getCookies(){
request('http://google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.headers);
}
})
}
Result
结果
{ date: 'Fri, 11 Dec 2015 07:15:50 GMT',
expires: '-1',
'cache-control': 'private, max-age=0',
'content-type': 'text/html; charset=EUC-KR',
p3p: 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
server: 'gws',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN',
'set-cookie':
[ 'PREF=ID=1111111111111111:FF=0:TM=1449818150:LM=1449818150:V=1:S=Q3BB20FA6TkaZymd; expires=Thu, 31-Dec-2015 16:02:17 GMT; path=/; domain=.google.co.kr',
'NID=74=hnriWxk7N9jHtP5W0qgaxrwD1YuNKOmJg748ucxWilu9jaqHJVovfkYdvMr0tlp-VToID5cdTNDSXNXqr4M8umJ9traab67x2xZKfu3hJbsBRXeVvyiCOcwZ8bkXNcU4; expires=Sat, 11-Jun-2016 07:15:50 GMT; path=/; domain=.google.co.kr; HttpOnly' ],
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' }
I want to pick up value of 'set-cookie' from response headers. How to pick it up? Is there any cool and simple way? Should I use for statement from filedkey, or. What should I do? I don't know I'm totally newbie on Javascript. Thanks...
我想从响应头中获取“ set-cookie”的值。怎么捡?有没有什么很酷很简单的方法?我应该使用来自filedkey的语句,还是。我该怎么办?我不知道我是 Javascript 的新手。谢谢...
采纳答案by BlackMamba
function getCookies(callback){
request('http://google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
return callback(null, response.headers['set-cookie']);
} else {
return callback(error);
}
})
}
then you can call:
然后你可以打电话:
getCookies(function(err, res){
if(!err)
console.log(res)
})
回答by brandonscript
Generally speaking with Node, if it's a common problem to solve, someone's already gone to the trouble to write and publish something on npm.
一般来说,对于 Node 来说,如果这是一个常见的问题需要解决,那么已经有人不厌其烦地在 npm 上编写和发布一些东西了。
For example, request-cookies!
例如,请求cookies!
In particular, I think you'll find the toJSON()method most helpful, though admittedly the package's documentation is rather light. You can check out the testsfor some working examples.
特别是,我认为您会发现该toJSON()方法最有帮助,尽管无可否认,该软件包的文档相当简单。您可以查看一些工作示例的测试。
That said, request already has some extensive documentation on cookies as well - you might find this suits your needs:
也就是说, request 已经有一些关于 cookie 的广泛文档 - 您可能会发现这适合您的需求:
Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set
jartotrue(either indefaultsoroptions).
默认情况下禁用 Cookie(否则,它们将在后续请求中使用)。要启用 cookie,请设置
jar为true(在defaults或 中options)。
(Scroll down to the bottom of the readmeto find the bits about cookies).
(向下滚动到自述文件的底部以查找有关 cookie 的内容)。
回答by thanhpk
Here is how you can use request-cookies as @brandonscript said.
这是@brandonscript 所说的如何使用请求 cookie 的方法。
var request = require('request');
var Cookie = require('request-cookies').Cookie;
request.get('https://google.com', function(err, response, body) {
var rawcookies = response.headers['set-cookie'];
for (var i in rawcookies) {
var cookie = new Cookie(rawcookies[i]);
console.log(cookie.key, cookie.value, cookie.expires);
}
});
Sample output from google:
来自谷歌的示例输出:
NID 98=FfYHDY9-40JzE78qxIpaMugODJ4y4zJIydluKUffvh1lDs70DYk7vrlmw2ca2gD54ywx5WV44Utz9EdLOdFE6IcW2BUGfiVpHZx3kWh69tT_eWlXZTiFkRo7TVr_9WWH 2017-09-08T04:22:41.000Z
回答by Junho Lee
When you import request module, probably you did it like this
当您导入请求模块时,您可能是这样操作的
var request = require('request');
Add one line as follows
添加一行如下
var request = require('request');
var request = request.defaults({jar: true})
And just use request module as usual. You can get the set cookie response.
并且像往常一样使用请求模块。您可以获取设置的 cookie 响应。
回答by BlackBeard
If you don't care what's in the cookieand you just want to use it, try this clean approach:
如果您不在乎里面有什么,cookie而只想使用它,请尝试这种干净的方法:
var request = require('request');
var j = request.jar();
var request = request.defaults({jar:j});
request('http://www.google.com', function () {
request('http://images.google.com', function (error, response, body){
// this request will will have the cookie which first request received
// do stuff
});
});
回答by jounieLW
Try doing this:
尝试这样做:
npm install tough-cookie
npm 安装硬饼干
const request = require("request");
const tough = require('tough-cookie');
const Cookie = tough.Cookie;
request.get(options, (error, response, body) => {
const cookie = Cookie.parse(response.headers['set-cookie'][0]);
console.log(cookie.cookieString());
});

