In a browser, if I send a GET request, the request will send the cookie in the meanwhile. Now I want to simulate a GET request from Node, then how to write the code?
3 Answers
Using the marvelous request library cookies are enabled by default. You can send your own like so (taken from the Github page):
var j = request.jar()
var cookie = request.cookie('your_cookie_here')
j.add(cookie)
request({url: 'http://www.google.com', jar: j}, function () {
request('http://images.google.com')
})

- 64,273
- 8
- 118
- 148
-
Ah: not sure. I've never tried using the default http client for my requests. – Femi Sep 06 '12 at 02:38
-
I just started to learn more about HTTP. I think that if default `http` module has the method to do that, I can know more details about it. – jiyinyiyong Sep 06 '12 at 02:49
-
3how do you get the cookies? I want to save them to a file and re-use them later. – chovy May 25 '14 at 02:38
-
1The add method doesn't work anymore. Use: j.setCookie(cookie, 'http://currentdomain.example.com/path', function(error, cookie) {}); – Nitin Bansal Mar 23 '15 at 17:52
If you want to do it with the native http:request()
method, you need to set the appropriate Set-Cookie
headers (see an HTTP reference for what they should look like) in the headers
member of the options
argument; there are no specific methods in the native code for dealing with cookies. Refer to the source code in Mikeal's request
library and or the cookieParser
code in connect
if you need concrete examples.
But Femi is almost certainly right: dealing with cookies is full of rather nitpicky details and you're almost always going to be better off using code that's already been written and, more importantly, tested. If you try to reinvent this particular wheel, you're likely to come up with code that seems to work most of the time, but occasionally and unpredicatably fails mysteriously.

- 14,795
- 5
- 33
- 35
var jar = request.jar();
const jwtSecret = fs.readFileSync(`${__dirname}/.ssh/id_rsa`, 'utf8');
const token = jwt.sign(jwtPayload, jwtSecret, settings);
jar.setCookie(`any-name=${token}`, 'http://localhost:12345/');
const options = {
method: 'GET',
url: 'http://localhost:12345',
jar,
json: true
};
request(options, handleResponse);

- 1,783
- 15
- 26
-
Please add more description and/or information about your answer and how it solves the asked problem so others can easily understand it without asking for clarification – koceeng Feb 23 '17 at 23:32