phantomjs XHR响应代码为空

时间:2018-04-12 04:30:32

标签: phantomjs

我使用以下代码自动化网页。网页有一个XHR调用,在提交表单时触发。通过使用“onResourceRequest”和“onResponseReceived”,我可以查看请求体,但响应状态代码始终为null。

PhantomJS版本:2.1.1

var page = require('webpage').create(), testindex = 0, loadInProgress = false;
var config = require('../../config/config.json');
var system = require('system');

console.log('Running Iteration 1 ...');

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
};

page.onError = function (msg, trace) {
    console.log(msg);
    trace.forEach(function(item) {
        console.log('  ', item.file, ':', item.line);
    });
};

page.onConsoleMessage = function(msg, lineNum, sourceId) {
    console.log(colors.cyan('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")'));
};

page.onLoadStarted = function() {
    loadInProgress = true;
    console.log("load started ", page.url);
};

page.onResourceRequested = function(request) {
    console.log('Request ' + request.url);
    console.log('Request Header :', JSON.stringify(request.headers));
    console.log('Request Body :', request.postData);
  };
  page.onResourceReceived = function(response) {
    console.log('Receive ' + response.url, response.status);
    if(response.status === null) {
        console.log(JSON.stringify(response));    
    }
  };

page.onLoadFinished = function() {
    loadInProgress = false;
    console.log("load finished ", page.url);
};

var steps = [
    function () {
        page.open(config.url, function (status) {
            if (status !== 'success'){
                console.log('Unable to access ', config.url); //This is a HTTPS endpoint
            } else {
                waitFor(function() {
                    // Check in the page if a specific element is now visible
                    return page.evaluate(function() {
                        return document.getElementById('code').value;
                    });
                }, function() {
                   console.log("The page dialog should be visible now.");
                //    phantom.exit();
                });
            }
        });
    }, 
    function () {
        var isPostMessageSupported = page.evaluate(function() {
            if(window.postMessage){
                return true;
            } else{
                return false;
            }
        });
        console.log('POST Message Support : ', isPostMessageSupported);
        var guid = page.evaluate(function() {
            return document.getElementById('guid').value;
        });
        console.log('GUID : ', guid);
        page.evaluate( function () {
            document.getElementById('userid').value = 'myusername';
            document.getElementById('pass').value = 'mypassword';
        });
    },
    function () {
        page.evaluate(function () {
            document.getElementById('myform').submit();
            return;
        });
    },
    function () {
        page.render('iteration1.png');
    },
];

function done(){
    console.log('##completed');
}

setInterval(function() {
    if (!loadInProgress && typeof steps[testindex] == "function") {
      console.log("step " + (testindex + 1));
      steps[testindex]();
      testindex++;
    }
    if (typeof steps[testindex] != "function") {
      console.log("test complete!");
      done();
      phantom.exit();
    }
}, 50);

我收到的XHR电话回复是

{"contentType":null,"headers":[],"id":42,"redirectURL":null,"stage":"end","status":null,"statusText":null,"time":"2018-04-12T04:15:04.402Z","url":"https://example.com/p"}

我已经尝试了所有的phantomJS命令行参数

phantomjs --web-security=false --ssl-protocol=tlsv1 --ignore-ssl-errors=true phantomjs/iterations/iteration1.js

我还尝试添加标题“Connection:keep-alive”。但没有解决我的问题。

我不确定这里会出现什么问题。

0 个答案:

没有答案