2014-04-14 57 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();