用phantomJS关闭

时间:2015-09-18 21:57:03

标签: javascript phantomjs

我使用phantomJS来填充服务中的数据。在下面的代码中设置了sessionToken但我无法在函数范围之外访问它。我知道我需要使用封口,但我还没有能够使用它。如何编写闭包以便我可以访问范围之外的变量?

var url = "https://securitybeta.srsplatform.com/WebServices/Srs.WebPlatform.WebServices.SrswpSite.SessionTokenService.svc/JSON/ISessionTokenServiceV2/CreateSessionToken?username=srsCore&password=[redacted]";

var page = require('webpage').create();

page.onResourceError = function(resourceError) {
        console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
        console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

var sessionToken = 0;

var getSessionToken = page.open(url, 'get', function(status) {
    sessionToken = page.plainText;
    sessionToken = JSON.parse(sessionToken);
    sessionToken = sessionToken.Item.AuthorizedSessionToken;

    console.log('Status: ' + status + ' sessionToken = ' + sessionToken);
    //console.log(sessionToken);
    return function () {
        return sessionToken;
    }

});
sessionToken = getSessionToken();
console.log('sessionToken outside of function scope: ' + sessionToken);

sessionToken将在以下代码中使用:

 var webPage = require('webpage');
var vehiclePage = webPage.create();
var settings = {
    operation: "POST",
    encoding: "utf8",
    headers: {
        "Content-Type": "application/json"
    },
    data: JSON.stringify({
        "VIN": "JF2SJAAC5EG432990",
        "StandardIds": null,
        "LicenseCountry": null,
        "LicensePlate": "334 142",
        "LicenseState": "UT",
        "OdometerUnitOfMeasure": 0,
        "UnitNumber": null,
        "Year": 1994,
        "Make": "Chevrolet",
        "Model": "Camaro",
        "Engine": null,
        "Color": null,
        "Description": null
    })
};

vehiclePage.onResourceError = function(resourceError) {
    console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
    console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

vehiclePage.open("https://ws-smsbeta.srsplatform.com/api/v1/Vehicle/Save?sessionToken=" + sessionToken + "&shopId=" + SHOP_ID, settings, function(status) {
    var vehicleGuid = vehiclePage.plainText;
    console.log('Status: ' + status + " " + vehicleGuid);
    phantom.exit();
});

0 个答案:

没有答案