如何从请求Nodejs获取数据

时间:2017-04-13 05:02:59

标签: node.js null request

代码:

    function getpage(link){
    var data = [];
    var options = {
    method: 'GET',
    uri: link,
    headers: {
        'Authorization': 'Basic ' + new Buffer("c64f80ba83d7cfce8ae74f51e263ce93:").toString('base64')
    }
    };
    request(options, function (err, response, body) {
       console.log( body );
       data.push(body);
    });
    return data;
}
console.log(getpage('https://docs.google.com/feeds/get_video_info?formats=ios&mobile=true&docid=0BxG6kVC7OXgrQ1V6bDVsVmJMZFU'));

但Dev Console中返回的数据为null。我做错了什么?

1 个答案:

答案 0 :(得分:0)

请求将来会给你一个结果。它的异步并以这种方式处理它。

第一种方法是使用回调函数 -

  function getpage(link, callback){
    var options = {
    method: 'GET',
    uri: link,
    headers: {
        'Authorization': 'Basic ' + new Buffer("c64f80ba83d7cfce8ae74f51e263ce93:").toString('base64')
    }
    };
    request(options, function (err, response, body) {
       callback(body);
    });
}

getpage('您的链接',console.log); //使用回调调用函数;

第二种方法,使用承诺(建议和简单) 然后使用Request-PromiseAxios库 -

var rp = require('request-promise');
rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...

    })
    .catch(function (err) {
        // Crawling failed...
    });