发送http头在表单提交CasperJS

Sending http headers in form submission CasperJS

本文关键字:表单提交 CasperJS http 发送      更新时间:2023-09-26

我用CasperJS做了以下测试步骤:

this.fillSelectors("#registration-form", {
    "#first-name": "Bob",
    "#last-name": "Smith",
    "#email-address": RANDOM_EMAIL,
    "#password": PASSWORD,
    "#password-confirm": PASSWORD
}, true);

我希望能够发送一个HTTP头与此。我似乎找不到一种不"手动"发布表单的方法,这不是我想要的那种测试。

有一个比下面这个更简单的方法。你可以访问PhantomJS的网页实例的casper.page.customHeaders属性。

casper.then(function() {
    casper.page.customHeaders = {
        "CuStOm": "Header"
    }; // set headers
    this.fillSelectors("#registration-form", { /*...*/ }, true);
});
casper.then(function() {
    casper.page.customHeaders = {}; // reset headers
});

问题是,这个方法将添加您的自定义头到每个请求,直到您再次禁用它。您可以尝试基于setTimeout或直接在fillSelectors之后重置标头。


您不能在浏览器中为表单提交设置标题。__utils__.sendAJAX也不提供自定义头。

您需要使用XMLHttpRequest来发送请求。下面的函数替换表单的提交处理程序来发送Ajax调用,并等待:

casper.thenFormToXHR = function(formSelector, data, customHeaders){
    this.thenEvaluate(function(formSelector, customHeaders){
        // see https://stackoverflow.com/a/19838177/1816580
        function submitForm(oFormElement) {
            window.__requestDone = false;
            var xhr = new XMLHttpRequest();
            for(var header in customHeaders) {
                xhr.setRequestHeader(header, customHeaders[header]);
            }
            xhr.onload = function(){
                window.__requestDone = true;
            };
            xhr.open (oFormElement.method, oFormElement.action, true);
            xhr.send (new FormData(oFormElement));
            return false;
        }
        document.querySelector(formSelector).onsubmit = submitForm;
    }, formSelector, customHeaders);
    this.then(function(){
        this.fillSelectors(formSelector, data, true);
    });
    this.waitFor(function check(){
        return this.evaluate(function(){
            return window.__requestDone;
        });
    });
};

你可以这样调用:

casper.thenFormToXHR("#registration-form", {
    "#first-name": "Bob",
    "#last-name": "Smith",
    "#email-address": RANDOM_EMAIL,
    "#password": PASSWORD,
    "#password-confirm": PASSWORD
}, {
    "X-Requested-With": "XMLHttpRequest" // here should be your custom headers
});

如果不需要等待XHR完成,可以减少代码:

casper.formToXHR = function(formSelector, data, customHeaders){
    this.evaluate(function(formSelector, customHeaders){
        // see https://stackoverflow.com/a/19838177/1816580
        function submitForm(oFormElement) {
            var xhr = new XMLHttpRequest();
            for(var header in customHeaders) {
                xhr.setRequestHeader(header, customHeaders[header]);
            }
            xhr.open (oFormElement.method, oFormElement.action, true);
            xhr.send (new FormData(oFormElement));
            return false;
        }
        document.querySelector(formSelector).onsubmit = submitForm;
    }, formSelector, customHeaders);
    this.fillSelectors(formSelector, data, true);
};