长期(好吧,3个月)读者,第一次发表的海报。我有一些客户端jquery AJAX请求的一些JSONP数据,我试图切换到http.request,所以我可以在Node.js服务器上使用它服务器端。
jQuery足够容易:JSfiddle here http://jsfiddle.net/gk0uttdu/,代码在这里:
$.ajax({
type: 'GET',
url: 'http://www.mysupermarket.co.uk/Api.aspx?Command={"Output":"JSONP","Commands":[{"Name":"Basket","Params":{"BrandStores":["780"],"ProductPrices":{"920":["ASDA","Ocado","Sainsburys","Tesco","Waitrose"],"016555":["ASDA","Sainsburys","Tesco","Waitrose"]},"TrolleyItems":["920","52200","1017"],"TrolleyLinks":["780"]}}]}&banner=34',
dataType: 'jsonp',
success: function(json) {
alert(JSON.stringify(json));
}
});
然而,当我尝试使用Node的http模块重写此请求时,如下所示,它失败了403.我怀疑是因为我没有在任何地方设置dataType:JSONP。
var ajaxUrl = 'http://www.mysupermarket.co.uk/Api.aspx?Command={"Output":"JSONP","Commands":[{"Name":"Basket","Params":{"BrandStores":["780"],"ProductPrices":{"920":["ASDA","Ocado","Sainsburys","Tesco","Waitrose"],"016555":["ASDA","Sainsburys","Tesco","Waitrose"]},"TrolleyItems":["920","52200","1017"],"TrolleyLinks":["780"]}}]}&banner=34';
var req = http.request(ajaxUrl, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('JSONP');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
console.log('data\n');
console.log('data\n');
req.end();
查看http文档并找不到如何设置它。还尝试了使用Matt的建议答案的Node请求模块,但未能使其工作。 Node HTTP request for Restful api's that return JSONP
这样做的正确方法是什么?感觉就像我一直撞在墙上几天,任何帮助都非常感激。
答案 0 :(得分:0)
需要伪造用户代理。使用Node中的“请求”模块。这工作
request({
headers: {
'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 6310.61.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.94 Safari/537.36',
},
uri: 'http://www.mysupermarket.co.uk/Api.aspx?Command={"Output":"JSONP","Commands":[{"Name":"Basket","Params":{"BrandStores":["780"],"ProductPrices":{"920":["ASDA","Ocado","Sainsburys","Tesco","Waitrose"],"016555":["ASDA","Sainsburys","Tesco","Waitrose"]},"TrolleyItems":["920","52200","1017"],"TrolleyLinks":["780"]}}]}&callback=jQuery17102980830231681466_1418310018496&_=1418220018508',
method: 'GET'
}, function (err, res, body) {
if (err) console.log(err)
else console.log('body', body);
});