带有ajax xml请求的Node js脚本不起作用

Node js script with ajax xml request not working

本文关键字:js 脚本 不起作用 Node ajax xml 请求 带有      更新时间:2023-09-26

我有一个使用节点(例如node runScript.js)运行的短javascript脚本。在它中,我使用了踮脚,并且尝试了各种检索xml文件的方法,但都没有成功。

tiptoe(
 	function getESData() {
 		var json;
                // get the json data.
	        for (var i = 0; i < json.hits.hits.length; i++) {	        	
	        	for (var multiId = 0; multiId < json.hits.hits[i]._source.multiverseids.length; multiId++) {
	        		var priceUrl = "http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s="+setName+"&p="+json.hits.hits[i]._source.name
					console.log("fetching " +priceUrl );
                  
                    // attempt 1:
					var x = new XMLHttpRequest();
					console.log("working"); // THIS CONSOLE LOG NEVER SHOWS UP.
					x.open("GET", priceUrl, true);
					console.log("working");
					x.onreadystatechange = function() {
						if (x.readyState == 4 && x.status == 200)
						{
							console.log(x.responseXML);
						}
					};
					x.send();
                  
                    // attempt 2:
					$.ajax({
						url: priceUrl,
						success: function( data ) {
						  console.log(data);
						}
					});
                  
                    // attempt 3:                  
					$.get(priceUrl, function(data, status){
				        console.log("Data: " + data + "'nStatus: " + status);
				    });
				}
			}
	    });
 	}
);

所有这些方法都会无声地失败(很明显,在测试时,我会注释掉除一个之外的所有方法,我不会同时使用所有三个方法),在打印第一个console.log(我在其中记录url以确保它有效)之后。(带有变量的url解析为这样的内容:http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=Ice Age&p=Arnjlot's Ascent,当我在浏览器中测试它时,它绝对会返回xml,所以我知道这是有效的)。是踮着脚尖的东西吗?

编辑:尝试4:

    $().ready(function () {
      console.log('working');
	  $.get(priceUrl, function (data) {
	    console.log(data);
	  });
	});

在"工作"日志显示在我的控制台中之前,这也会失败。不确定这是否重要,但我也使用了gitbash控制台。

编辑2:答案是使用request,方法如下:

request(priceUrl, function(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
})

效果很好。

另一个访问控制允许来源问题。我试过你给出的链接:

XMLHttpRequest无法加载http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=冰%20Age和amp;p=Arnjlot%27s%20气味。请求的资源上不存在"Access Control Allow Origin"标头。因此,不允许访问源"null"。

这里有一篇关于可能的解决方案的文章。

在您的情况下,您可以对请求使用jsonp数据类型,这只适用于jQuery 1.12/2.2+:

var url = "http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=Ice Age&p=Arnjlot's Ascent";
$.get({
    url: url,
    dataType: 'jsonp text xml'
}, function(data, status) {
    console.log("Data: " + data + "'nStatus: " + status);
});