Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I send a GET request with cookies in the headers in Node?

Tags:

node.js

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?

like image 237
jiyinyiyong Avatar asked Sep 06 '12 02:09

jiyinyiyong


People also ask

Can you set cookie in GET request?

Can you set cookie in GET request? To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way.

How do I send cookies in a post request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons.

Can we send body in GET request in node JS?

You can not add body to a get request, you will have to add a query string for the request to send those data.


2 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')
})
like image 189
Femi Avatar answered Oct 14 '22 06:10

Femi


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.

like image 39
ebohlman Avatar answered Oct 14 '22 06:10

ebohlman