Skip to content Skip to sidebar Skip to footer

Pass Cookie As Part Of Node.js Request

I am using the request package to create my server side requests. I wrote authentication middleware that checks for a cookie/session id for all requests. Therefore, is there a way

Solution 1:

Let me explain about cookies and that will probably show you why it's hard to get the cookie you want.

  1. When your user's browser logs into http://localhost:3000, that server creates a login cookie and returns it as part of the login response.
  2. When the browser receives that cookie, it saves that cookie persistently within the browser and it associates that cookie with the http://localhost:3000 domain and port.
  3. When the user again makes a request to http://localhost:3000, the browser sends all cookies it has previously saved for that particular domain and port with the request to the server.
  4. When the server receives the request, it can examine any cookies that are sent with the request.
  5. When the browser then makes a request to a different server or even the same server, but on a different port, the browser does NOT send the previously saved cookies with that request because those cookies belong to a different server and port. The browser goes to great security lengths to send cookies only to the servers that the cookies belong to. Since cookies often provide login access, you can clearly see why it's important that things like login credential cookies are not sent to servers they should not be sent to.

Now, on to your node.js code. You show a block of node.js code that is trying to access the same http://localhost:3000 server. But, the cookies are stored in the user's browser. Your node.js code cannot get them from the browser as the browser guards them and will only reveal them when the browser itself sends a request to http://localhost:3000.


If you do actually have the right cookie in your node.js code, then you can set it on your request like this:

request({url: 'http://localhost:3000/users/api', headers: {Cookie: somedataHere}}, function(error, response, body) {
    console.log(body); //this console.logs my login page since requests w/o valid cookies get redirected to login
    res.render('../views/admin');
});

Relevant documentation for custom headers in the request module is here.

Solution 2:

Answer:

var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
   'User-Agent': 'request'.
   'host': 'localhost:3000',
   'cookie': cookieText //this is where you set custom cookies
  }
};

functioncallback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}

request(options, callback);

Post a Comment for "Pass Cookie As Part Of Node.js Request"