如何从upc数据库请求中提取数据

时间:2014-04-14 15:56:08

标签: node.js http

在我的项目中我必须向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,我不知道在哪里可以找到数据

1 个答案:

答案 0 :(得分: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();
相关问题