Search code examples
node.jsajaxcookiesxmlhttprequest

Node.js - How to set cookies on http request


I've tried this but couldn't get it to work. I make a jQuery ajax request to log in to a Drupal system with xhrFields withCredentials set to true. Server returns the session name and id. So I guess my question is; how would I set those withCredentials with request as it is done with ajax call?

var cookie = request.cookie(app.session.sessionName + '=' + app.session.sessionId);

progress(request(url), {
    header: {
        'Cookie': cookie
    }
})

// Access denied [Anonymous user]

Solution

  • Setting the header does not work but I found the solution (which was actually in the docs);

    var request = require('request');
    var j = request.jar();
    var cookie = request.cookie(app.session.sessionName + '=' + app.session.sessionId);
    j.setCookie(cookie, url);
    
    request({url: url, jar: j})
    //....
    

    Later you can see the cookie on end event;

    //var cookie_string = j.getCookieString(url);
    //console.log('Cookie: ', cookie_string);