My http response code from NightmareJS is undefined

375 views Asked by At

Hi & welcome to 2017 :)

I am trying out NightmareJS in place of PhantomJS and so far so good (PhantomJS is performing very slowly for me hence the change)

My issue is when I try and return the http response header, the value is undefined.

I have looked through the docs and many examples and they all point show very similar code to mine.

I am checking the site/s I am opening by setting show to true so I know they actually open

Any help appreciated, cheers.

My current code is below:

var Nightmare = require('nightmare');

var nightmare = Nightmare({
    show: false,
    switches: {
        'ignore-certificate-errors': true
    },
    webPreferences:{
        images: true
    },
    //waitTimeout: 1000,
    loadTimeout: 30000 //** If we cant reach the page after nnnn millseconds, timeout
});

//** Start nightmare
var ms = Date.now(); //** Set a timer
nightmare
.cookies.clearAll()
.goto(url)
.screenshot('abc123.png')
.end()
.then(function(httpResponse){
    console.log(httpResponse.code); //** <<<< Here SHOULD be the http response code
    console.log(Date.now() - ms);
    callback(siteObject); //
})
.catch(function (error) {
    console.error('Search failed:', error);
});
1

There are 1 answers

3
Daniel On BEST ANSWER

The problem happens because of the line

.screenshot('abc123.png')

If you remove it, then httpResponse.code will return a status code.

I believe this might be a bug - I have opened an issue with the developers, and I will get back to you with the response.

Update

I just received a reply from rosshinkley who is the largest contributor to nightmarejs:

httpResponse is not defined because the parameters passed to .then() will be from the last action executed in the chain (with the exception of .end()) - in your case, .screenshot() (which doesn't return anything). If you need the HTTP response, you can break up your chain with another .then() to perform logic.

The original question can then be fixed with (again credit to rosshinkley):

nightmare.goto(url)
.then(function(httpResponse) {
  if(httpResponse.code == 200) {
    return nightmare.screenshot('abc123.png');
  } 
  else {
    //error condition?
    throw new Error('http response was not ok');
  }
})
.then(function(){ return nightmare.end(); })