我使用chrome的cookies.txt扩展名登录到Google后获得cookies.txt。 cookie文件格式为netscape cookie。现在,我想将此cookie文件通过nodejs传递给http请求。
我使用的命令行:
curl -L -b cookie.txt https://myaccount.google.com/
但是我找不到任何文档来告诉我如何将cookie文件传递给nodejs的curl函数。 如何将上述命令行转换为nodejs?
更新: cookie.txt格式如下:
# HTTP Cookie File for mozilla.org by Genuinous @genuinous.
# To download cookies for this tab click here, or download all cookies.
# Usage Examples:
# 1) wget -x --load-cookies cookies.txt "https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Functions/Arrow_functions"
# 2) curl --cookie cookies.txt "https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Functions/Arrow_functions"
# 3) aria2c --load-cookies cookies.txt "https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Functions/Arrow_functions"
#
.mozilla.org TRUE / FALSE 1643553591 _ga GA1.2.176633766.1564724252
.developer.mozilla.org TRUE / TRUE 1583073592 dwf_sg_task_completion False
.mozilla.org TRUE / FALSE 1580567991 _gid GA1.2.1169610322.1580463999
developer.mozilla.org FALSE / FALSE 1580483392 lux_uid 158048125271715522
.mozilla.org TRUE / FALSE 1580481652 _gat 1
Nodejs代码:
var http = require('http');
var options = {
hostname: 'www.myaccount.google.com',
path: '/',
headers: {
'User-Agent': 'whatever',
'Referer': 'https://google.com/',
'Cookie': ????
}
};
http.get(options, callback);
答案 0 :(得分:1)
如您所知,您只需要根据名称和与目标主机名相对应的值来设置Cookie
标头。以下是您的developer.mozilla.org
域的Cookie文件中的示例:
var http = require('http');
var options = {
hostname: 'developer.mozilla.org',
path: '/',
headers: {
'User-Agent': 'whatever',
'Referer': 'https://google.com/',
'Cookie': 'dwf_sg_task_completion=False; lux_uid=158048125271715522;'
}
};
http.get(options, callback);
答案 1 :(得分:1)
有npm cookiefile软件包。它可以读取netscape格式的cookie文件并生成适当的标头。
它将从cookie文件发送cookie及其所有过期,路径和范围数据。
类似这样的东西(未调试):
var http = require('http');
const cookiefile = require('cookiefile')
const cookiemap = new cookiefile.CookieMap('path/to/cookie.txt')
const cookies = cookiemap.toRequestHeader().replace ('Cookie: ','')
var options = {
hostname: 'www.myaccount.google.com',
path: '/',
headers: {
'User-Agent': 'whatever',
'Referer': 'https://google.com/',
'Cookies': cookies
}
};
http.get(options, callback);