Search code examples
node.jsnode-request

request callback, can't acces error, response and body


I'm creating an https request, to get some hidden variables on a sign in page. I'm using the node.js package request for this. After calling the request, I'm using a callback to go back to my parse function.

class h {
    constructor(username, password){
        this.username = username;
        this.password = password;
        this.secret12 = '';
    }

    init() {
        //Loading H without cookie
        request({
                uri: "http://example.com",
                method: "GET",
                jar: jar,
                followRedirect: true,
                maxRedirects: 10,
                timeout: 10000,
                //Need to fake useragent, otherwise server will close connection without response.
                headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
            },
            this.getHiddenInputs());
    }

    getHiddenInputs(error, response, body) {

            if (!error && response.statusCode === 200) {
                //Parsing body of request, to get hidden inputs required to mock legit authentication.
                const dom = new JSDOM(body);
                this.secret12 = (dom.window.document.querySelector('input[value][type="hidden"][name="secret12"]').value);
            }
            else {
                console.log(error);
                console.log(response.statusCode)
            }
        };
}
const helper = new h("Username", "Password");

helper.init();
console.log(helper);

So after calling request inside init(). I'm using the callback function to run the code that finds the Hidden Input after it has completed the request. I'm following the example from here.

Am I missing something?


Solution

  • You are executing this.getHiddenInputs() instead of passing it to request as a callback, so there is no actual callback given to the request call.

    You could pass it like this this.getHiddenInputs.bind(this) or I'd prefer something like this (error, response, body) => this.getHiddenInputs(error, response, body)