How to get response status 404 in casper.js within thenOpen instead of undefined?

我与影子孤独终老i 提交于 2020-01-03 15:55:27

问题


Any idea why code below doesn't catch 404 in either response var or in the http.status.404 event?

I run this with phantomjs 1.9, casperjs 1.0.2 and Windows 7

var casper = require("casper").create(),
    utils = require('utils');

casper.start();

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
  casper.capture('test.png');
  utils.dump(response);
});

casper.on('http.status.404', function(resource) {
  this.echo('wait, this url is 404: ' + resource.url);
});

casper.run(function() {
  console.log('End');
  casper.exit();
});

Ideally I like to catch 404 within thenOpen(). How to do that?

UPDATE 1:

I tried this

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
  casper.capture('test.png');
  utils.dump(response);

    if(this.status(false)['currentHTTPStatus'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }

});

And here is the output:

undefined
No Error 404
End

It still doesn't make sense.

UPDATE 2:

I tried 404checker.js here https://gist.github.com/n1k0/4509789

casperjs 404.js http://www.google.com/sadfafsdgfsd

Output:

URI.js loaded
Starting
http://www.google.com/sadfafsdgfsd
http://www.google.com/sadfafsdgfsd is okay (HTTP 200)
1 new links found on http://www.google.com/sadfafsdgfsd
All done, 1 links checked.

So what's going on!?


回答1:


I just ran your code and it seems to be working fine for catching the 404 error in the on event. If you want to catch it within the thneOpen(), something like this would work:

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function() {
    if(this.status(false)['currentHTTPStatus'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }
});

Or you could use the response directly, response['status'] will be 404 in this case.

casper.thenOpen('http://www.google.com/sadfafsdgfsd', function(response) {
    if(response['status'] === 404) {
        console.log('Error 404');
    } else {
        console.log('No Error 404');
    }
});


来源:https://stackoverflow.com/questions/18074093/how-to-get-response-status-404-in-casper-js-within-thenopen-instead-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!