Skip to content

Instantly share code, notes, and snippets.

@zhenwusw
Created June 4, 2016 16:49
Show Gist options
  • Save zhenwusw/59f266c0759c336a2f210ee646080ec3 to your computer and use it in GitHub Desktop.
Save zhenwusw/59f266c0759c336a2f210ee646080ec3 to your computer and use it in GitHub Desktop.

Revisions

  1. zhenwusw created this gist Jun 4, 2016.
    61 changes: 61 additions & 0 deletions casperjs-webserver.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    var utils = require('utils');
    var server = require('webserver').create();
    var casper = require('casper').create({
    pageSettings: {
    loadImages: true,
    webSecurityEnabled: false
    },
    verbose: true,
    logLevel: "debug"
    });

    function neverendingWait(){
    this.wait(30*1000, neverendingWait);
    }

    casper.responseOk = function(request, response, data) {
    response.statusCode = 200;
    response.headers = {
    'Cache': 'no-cache',
    'Content-Type': 'text/plain;charset=utf-8'
    };
    response.write(JSON.stringify(data, null, null));
    response.close();
    }

    casper.responseNotFound = function(request, response) {
    response.statusCode = 404;
    response.headers = {
    'Cache': 'no-cache',
    'Content-Type': 'text/plain;charset=utf-8'
    };
    response.write('Something went wrong, dude!')
    response.close();
    }

    casper.checkCaptcha = function() {
    this.echo('# start listening on 8585 ...', 'debug');
    server.listen('127.0.0.1:8585',{'keepAlive': true}, function (request, response) {
    this.echo(utils.dump(request), 'debug');
    switch (request.url) {
    case '/code_image':
    var based64Image = this.captureBase64('png', 'img#verifycode1');
    this.responseOk(request, response, {code_image: based64Image});
    break;
    case '/code_result':
    var codeResult = JSON.parse(request.post);
    this.responseOk(request, response, codeResult);
    break;
    case '/captcha_result':
    var captchaResult = JSON.parse(request.post);
    this.responseOk(request, response, captchaResult);
    break;
    default:
    this.responseNotFound(request, response);
    }
    }.bind(this));
    }

    casper.start('http://localhost:4567/form').then(function(){
    this.checkCaptcha();
    }).then(neverendingWait).run();