Pass cookie as part of node.js request

38,100

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
  }
};

function callback(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);
Share:
38,100
Trung Tran
Author by

Trung Tran

Updated on July 29, 2022

Comments

  • Trung Tran
    Trung Tran almost 2 years

    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 I include the user's cookie as part of the request? Here is my current code:

    var cookie = parseCookie.parseCookie(req.headers.cookie);
    
    request('http://localhost:3000/users/api', 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');
    });
    

    Currently, this returns 'no cookie found' in the console. However, if I turn off my authentication middleware, the code above works as intended.

    Additional info:

    The cookie I want is the end user's cookie located on the browser. The end user's cookie is created by the app whenever the user logs in.

    Update - solution attempt 1:

    I tried this from the documentation:

    var cookie = parseCookie.parseCookie(req.headers.cookie);
    var cookieText = 'sid='+cookie;
    var j = request.jar();
            var cookie = request.cookie(cookieText);
            var url = 'http://localhost:3000/users/api';
            j.setCookie(cookie, url);
            request({url: url, jar: j}, function(error, response, body) {
                request('http://localhost:3000/users/api');
            });
    

    However, the console is still returning 'no cookie found'

    Can someone help?

    Thanks in advance!

  • Trung Tran
    Trung Tran over 8 years
    Right, but my first line of code contains the cookie. So I technically already have the cookie, which I am trying to pass as part of my request function.
  • jfriend00
    jfriend00 over 8 years
    @user1547174 - If you actually have the right cookie, then you can just add it as a header to the request you are sending as I now show at the end of my answer.
  • Trung Tran
    Trung Tran over 8 years
    I found that momentarily afterwards. Thanks a lot!!
  • Alexander Mills
    Alexander Mills almost 7 years
    does this work? maybe add some text explaining why it's different from OP
  • Alexander Mills
    Alexander Mills almost 7 years
    for example, what is parseCookie?
  • Vasyl Boroviak
    Vasyl Boroviak over 5 years
    It can be "cookie-parser" NPM module. E.g.: router.use(require("cookie-parser")()). Then you get this property req.cookies in your express.js handlers.