【问题标题】:Get ajax request with nightmare js使用噩梦 js 获取 ajax 请求
【发布时间】:2017-08-04 20:51:23
【问题描述】:

所以,我正在使用 nightmare js,并且我喜欢模拟登录过程,为此我使用了这样的 nightmarejs

function testiiing(){
    nightmare
          .goto('http://localhost:4200/login')
          .type('#name', 'test')
          .type('#pwd', 'test')
          .click('#log')
          .evaluate(function() {
            return //something
          })
          .then(function(result) {
            console.log(result);
          })
          .then(function() {
            console.log('done');
          })
          .catch(function(error){
            console.error('an error has occurred: ' + error);
          });
}

问题是我想将“//something”更改为可以返回“name=test&pwd=test”的东西(所以 ajax 发布请求),有人可以帮助我或告诉我是否可以全部?

【问题讨论】:

  • 嗨,我的回答对你有帮助吗?
  • 嗨,安德鲁,如果我能找到一种方法让噩梦接受“$”参数,这可能会有所帮助,自从你回答我以来,我一直在寻找一种方法^^
  • 对不起什么?你不是在用 jQuery 吗?
  • 我们通常可以在 nightmarejs 中注入 jquery,但我现在无法实现 x)

标签: javascript ajax post nightmare


【解决方案1】:

没有使用噩梦 js 的经验,但由于您已标记 jQuery,因此只需使用 .serialize()

https://api.jquery.com/serialize/

.serialize() 方法以标准 URL 编码表示法创建文本字符串。它可以作用于已选择单个表单控件的 jQuery 对象,例如 <input><textarea><select>$( "input, textarea, select" ).serialize();

例子:

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
  console.log( $( this ).serialize() );
});

这应该完全符合您的要求。

对于您的具体示例,还请查看.serializeArray()

【讨论】:

    【解决方案2】:

    我知道这很旧,但这对我来说也很棘手。这就是我正在使用的并且有效:

    test(){
            let selector = "#twd";
            return this.nightmare
            .goto("https://time.is/")
            .inject("js", "jquery.js")  //actually injects jquery, which doesn't exist on the site
            .evaluate((selector) =>{
                return new Promise((resolve, reject) =>{
                    // resolve(document.querySelector(selector).innerHTML)
                    $.ajax({
                        url: "https://jsonplaceholder.typicode.com/posts",
                        type: "POST",
                        data: {foo: "bar"},
                    })
                    .then(response =>{
                        resolve(response) //resolve the promise from browser and resume execution in node
                    })
                })
            }, selector) //can only pass in one param
            .then(result =>{
                let x = result;
            })
        }
    
      //result = {id: some number}
    

    注意选择器,它必须是一个参数,如果你想要更多的键值,它必须是一个对象。在这个糟糕的例子中实际上并没有使用它,但这只是一个糟糕的例子。

    无论出于何种原因,评估回调中的 js 样式都可以处理 es6 样式的代码。

    另外,内部的 Promise 链与外部的完全不同。评估中的所有内容都在电子而不是您的节点服务器中运行。但是一旦你解决了,它就会在节点中恢复。

    【讨论】:

    • 为什么需要注入jquery?你不能使用普通的 XMLHttpRequest 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2010-12-21
    相关资源
    最近更新 更多