使用PhantomJS处理多个用户对多个远程Web表单的请求 [英] Handle multiple users requests to multiple remote web forms using PhantomJS

查看:99
本文介绍了使用PhantomJS处理多个用户对多个远程Web表单的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NightmareJS创建了一个ExpressJS应用程序,该应用程序具有一个表单,当我们填写并提交表单时,它将请求发送到一些远程表单并计算数据并返回这些结果.但是问题是,仅当单个客户提交表单时,它才有效.当多个客户同时提交表单时,它将不起作用.这可能是什么原因以及如何解决这个问题?

I created a ExpressJS application using NightmareJS which has a form and when we fill form and submit, it sends requests to some remote forms and calculate data and return those results. But the problem is it only works when single client submit the form. When multiple clients submit the form at same time it doesn't work. What could be the reason for this and how to solve this?

前端JS脚本

$(document).ready(function () {

$("#calculate-form").submit(function (event) {
    var request;

    if (request) {
        request.abort();
    }

    var $form = $(this);

    var $inputs = $form.find("input, select, button, textarea");

    var serializedData = $form.serialize();

    $inputs.prop("disabled", true);

    form1(request, serializedData, $inputs, '/example1', '#form1');

    function form1(request, serializedData, inputs, appUrl, displayElement)
    {
        request = $.ajax({
            url: appUrl,
            type: "post",
            data: serializedData
        });



        request.done(function (response) {
            $(displayElement).text(response.value);

            form2(request, serializedData, $inputs, '/example2', '#form2');

            function form2(request, serializedData, inputs, appUrl, displayElement)
            {
                request = $.ajax({
                    url: appUrl,
                    type: "post",
                    data: serializedData
                });

                request.done(function (response) {
                    $(displayElement).text(response.value);
                });

                request.fail(function (jqXHR, textStatus, errorThrown) {
                    console.log("Failed");
                });
            }
        });

        request.fail(function (jqXHR, textStatus, errorThrown) {
            console.log("Failed");
        });
    }

    event.preventDefault();
});
});

ExpressJS索引脚本

ExpressJS index script

var express = require('express');
var app = express();
var phantom = require('phantom');
var bodyParser = require('body-parser');
var Nightmare = require('nightmare');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/'));
app.engine('html', require('ejs').renderFile);
app.get('/', function (request, response) {
   response.render('index.html');
});
app.listen(app.get('port'), function () {
   console.log('Scrapper is running on port', app.get('port'));
});

require('./form1')(app, Nightmare);
require('./form2')(app, Nightmare);

ExpressJS form1脚本

ExpressJS form1 script

module.exports = function (app, Nightmare) {

var nightmare1 = Nightmare({
    show: true
});


app.post('/example1', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader('Content-Type', 'application/json');
    try
    {
        if (req.method === 'POST') {
            var requestParams = req.body;
            nightmare1

                    .goto('https://example1.com/form')
                    .evaluate(function () {
                        var select = document.querySelector('#RepaymentMethod');
                        select.value = "1";
                        select.dispatchEvent(new Event('change'));
                    })
                    .wait("#formbtn-1")
                    .evaluate(function () {

                        document.getElementById('inputfield_1').value = "inputfield-1-Value";

                        document.getElementById('btnSubmitform').click();

                    })
                    .wait("#resultvalue")
                    .evaluate(function () {

                        var str = document.querySelector('#resultvalue').innerText;
                        return res;

                    })
                    .end()


                    .then(function (form1) {
                        res.send({value: form1});
                        nightmare1.halt();
                    })

                    .catch(function (error) {
                        res.send({'error': error});
                        nightmare1.halt();
                    });
        }
    } catch (err)
    {
        res.sendStatus(400).send(err);
        nightmare1.halt();
        process.exit();
    }
});
}

ExpressJS form2脚本

ExpressJS form2 script

module.exports = function (app, Nightmare) {

var nightmare2 = Nightmare({
    show: true
});


app.post('/example2', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader('Content-Type', 'application/json');
    try
    {
        if (req.method === 'POST') {
            var requestParams = req.body;
            nightmare2

                    .goto('https://example2.com/form')
                    .evaluate(function () {
                        var select = document.querySelector('#RepaymentMethod');
                        select.value = "10";
                        select.dispatchEvent(new Event('change'));
                    })
                    .wait("#formbtn-1")
                    .evaluate(function () {

                        document.getElementById('inputfield_1').value = "inputfield-1-Value";
                        document.getElementById('inputfield_2').value = "inputfield-2-Value";

                        document.getElementById('btnSubmitform').click();

                    })
                    .wait("#resultvalue")
                    .evaluate(function () {

                        var str = document.querySelector('#resultvalue').innerText;
                        return res;

                    })
                    .end()


                    .then(function (form2) {
                        res.send({value: form2});
                        nightmare2.halt();
                        process.exit();
                    })

                    .catch(function (error) {
                        res.send({'error': error});
                        nightmare2.halt();
                        process.exit();  
                    });
        }
    } catch (err)
    {
        res.sendStatus(400).send(err);
        nightmare2.halt();
        process.exit();
    }
});
}

推荐答案

基于您发布的示例,您试图在多个请求中重复使用同一噩梦实例.好像您有多个请求一样,这将不起作用,以后的请求的操作将被添加到当前正在执行的上下文中.这更加复杂,因为您还要.end()实例,使Nightmare实例在初始请求后无法使用.

Based on the example you posted, you're trying to re-use the same Nightmare instance across multiple requests. This won't work as if you have multiple requests come in, the actions for the later requests will be added to the currently executing context. This is further complicated because you're also .end()ing the instance, rendering the Nightmare instance unusable after the initial request.

如果将梦m实例化到Express post方法中,可能会带来更好的运气,但请注意:此方法的伸缩性不是特别好.

If you move the Nightmare instantiation into the Express post method, you will likely have better luck, but be careful: this method will not scale particularly well.

这篇关于使用PhantomJS处理多个用户对多个远程Web表单的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆