Search code examples
node.jsunirest

Cant seem to make cookie authenticated requests using Unirest


I'm trying to use the Unirest Jar feature to make session authenticated requests however I cant seem to get my name console logged. The following is sample code Im using. Any ideas on how I can get my name console logged?

var cheerio = require('cheerio');
var unirest = require('unirest');
var CookieJar = unirest.jar();
var twitterLogin = 'https://twitter.com/sessions';
var twitterUsername = 'TWITTERUSERNAME';
var twitterPassword = 'TWITTERPASSWORD!'

var Request = unirest.get('https://twitter.com/login').jar(CookieJar);
Request.end(function(response) {
    var $ = cheerio.load(response.body);
    var authToken = $('input[name="authenticity_token"]').val();
    console.log(authToken)
    unirest.post(twitterLogin)
        .jar(CookieJar)
        .followRedirect(true)
        .header('Referer', 'https://twitter.com/login')
        .header('content-type', 'application/x-www-form-urlencoded')
        .header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36')
        .field('authenticity_token', authToken)
        .field('session[username_or_email]', twitterUsername)
        .field('session[password]', twitterPassword)
        .end(function(response) {
            console.log(response.statusCode)
            console.log(response.body)
            unirest.get('https://twitter.com')
                .jar(CookieJar)
                .followRedirect(true)
                .end(function(response) {
                    var $ = cheerio.load(response.body)
                    console.log($('.DashboardProfileCard-name').text());
                })

        })
});

Solution

  • From the docs:

    Request.jar(Boolean) or Request.jar(Jar)

    Sets jar, cookie container, on Request.options. When set to true it stores cookies for future usage.

    You should call unirest.jar() with true as argument:

    var CookieJar = unirest.jar(true);