2014-04-14 54 views
1

在我的项目我必须做upcDatabase.com的请求,我与nodeJS工作,我从服务器得到的答案,但我不怎么提取数据这是我的重要部分代码:如何从upcdatabase请求提取数据

module.exports = function (http,upc){  
var upc_ApiKey = "XXX", 
url = "http://upcdatabase.org/api/json/"+upc_ApiKey+'/'+upc; 
http.get(url,function(resp){ 
// my code to read the response 

我没有得到任何错误,但RESP是一个很大的JSON和我不知道去哪里找数据

回答

2

我会建议你使用superagent模块。它提供比内置http请求更多的功能,它会自动为您分析响应。

request 
    .get(url) 
    .end(function(err, res) { 
     if (res.ok) { 
      // Her ethe res object will be already parsed. For example if 
      // the server returns Content-Type: application/json 
      // res will be a javascript object that you can query for the properties 
      console.log(res); 
     } else { 
      // oops, some error occurred with the request 
      // you can check the err parameter or the res.text 
     } 
    }); 

你可以达到同样的与内置的HTTP模块,但有更多的代码:

var opts = url.parse(url); 
opts.method = "GET"; 
var req = http.request(opts, function (res) { 
    var result = ""; 

    res.setEncoding("utf8"); 
    res.on("data", function (data) { 
     result += data; 
    }); 
    if (res.statusCode === 200) { 
     res.on("end", function() { 
      // Here you could use the result object 
      // If it is a JSON object you might need to JSON.parse the string 
      // in order to get an easy to use js object 
     }); 
    } else { 
     // The server didn't return 200 status code 
    } 
}); 

req.on("error", function (err) { 
    // Some serious error occurred during the request 
}); 

// This will send the actual request 
req.end();