简体   繁体   English

Node.js服务器中的同步Ajax

[英]Synchronous ajax in node.js server

I am trying to get html code from a series of cross domain urls with my node.js server using this function I have pasted in. If I do this asynchronously, I am successful at getting the needed html; 我正在尝试使用粘贴的此功能通过我的node.js服务器从一系列跨域URL中获取html代码。如果我以异步方式执行此操作,则可以成功获取所需的html。 however, I am having a hard time getting everything else that goes on outside of this function to work properly. 但是,我很难让此功能之外的所有其他功能正常工作。 Doing this synchronously, as I have it now, makes everything outside of this function work the way it should, but none of my ajax calls are successful and this.url is undefined. 像现在一样,同步执行此操作可使该函数之外的所有内容按应有的方式工作,但是我的ajax调用均未成功,并且this.url是未定义的。

I am using the jquery node module to do this btw. 我正在使用jquery节点模块来完成此操作。

This is the error that gets logged in the console : [TypeError: Cannot read property 'headers' of undefined] 这是在控制台中记录的错误:[TypeError:无法读取未定义的属性'headers']

Any help would be greatly appreciated. 任何帮助将不胜感激。

function myFunction( catname, myurl ){

var htmlresult="";

  $.ajax({
    type: "GET",
    url : "http://"+myurl,
    dataType: 'html',
    context: this,
    async: false,
    cache: false,
    error: function(xhr, status, ethrown){
      console.log("THERE WAS AN ERROR");
      console.log(this.url);
      console.log(catname);
      console.log(status);
      console.log(ethrown);

      htmlresult = myurl;
    },
    success : function(result){
      console.log(this.url);
      console.log("SUCCESS");
      console.log(catname);
      //console.log(result);

      htmlresult = result;
    }
})

return htmlresult;
}

Thank you for taking the time to read this. 感谢您抽出时间来阅读。

You should not really use the synchronous request mode in this case to do your job. 在这种情况下,您不应该真正使用同步请求模式来完成您的工作。 If you are using node and want to carry out some work in a synchronous fashion you should use promise/deffered concept. 如果您正在使用节点并希望以同步方式执行某些工作,则应使用Promise / Deffered概念。 See example below 见下面的例子

var Deferred = require("promised-io/promise").Deferred;
var def = new Deferred();

request(this.getUrl("statusObject"), function(err, resp, body) {
    if(!err){
        def.resolve(body);
    }
}

def.promise.then(function(val){
    //Do something.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM