Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass the cookie file into the curl request nodejs

I use cookies.txt extension of chrome to get cookies.txt after login to google. The cookie file format is netscape cookie. Now I want pass this cookie file to http request by nodejs.

Command line I used:

curl -L -b cookie.txt https://myaccount.google.com/

But I couldn't find any documents that tell me about how to pass cookie file to curl function of nodejs. How to convert the above command line to nodejs?

Update: cookie.txt format like this:

# 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 code:

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);
like image 907
justcntt Avatar asked Oct 27 '25 05:10

justcntt


1 Answers

There's the npm cookiefile package. It can read the netscape-format cookiefile and generate the appropriate header.

It will send the cookies with all their expiration, path, and scope data from the cookiefile.

Something like this (not debugged):

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);
like image 139
O. Jones Avatar answered Oct 28 '25 19:10

O. Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!