如何从upcdatabase请求中提取数据

在我的项目中,我不得不对upcDatabase.com做一个请求,我正在使用nodeJS,我从服务器得到答案,但是我不知道如何提取数据,这是我的代码的重要部分:

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,我不知道在哪里可以find数据

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

 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();