http.get和node.js以及JSON

时间:2013-01-16 13:28:06

标签: php javascript node.js json

我尝试开发一个基于node.js构建的Web应用程序,它与PHP API交互。以下我试图请求一个JSON对象,我的PHP api创建。我想做的就是获取它然后在我的.ejs模板中使用。

这是我的节点代码,

/*
 * GET home page.
 */

 //var request = require('reqeust');
 var http = require('http');
 var body = "";

exports.index = function(req, res){

    var options = {
        host: 'api.dev.com',
        port: 80,
        path: '/api/v1/posts',
        method: 'GET'
    };

    http.get(options, function(res) {
      console.log("Got response: " + res.statusCode);
      console.log(res);
      res.on("data", function(chunk) {
        console.log("BODY: " + chunk);
      });
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    });

    res.render('index', { data: body });
};

EJS

<%= data.title %>

但是data.title返回未定义,我的JSON对象如下所示,并且有效。

[{"title":"This is the title of post 1","extract":"This is just a proof of concept more than anything at the moment","body":"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n \t\t\t\tCras sed tellus massa, at commodo lectus. Ut metus nulla, sollicitudin id mollis ac, \n \t\t\t\tmalesuada eget libero. Duis sit amet auctor metus. Suspendisse et ornare dolor.\n \t\t\t\tMorbi non sodales sem. Nunc semper hendrerit dignissim. Proin id mollis purus.\n \t\t\t\tProin leo leo, feugiat ac sodales in, laoreet quis nisl. Etiam sed enim in libero\n \t\t\t\tpellentesque porttitor id eget diam.<\/p>","date_created":"01\/01\/2013 13:08:45","author":"Simon"}]

2 个答案:

答案 0 :(得分:1)

尝试使用request模块,这样您就不必处理块。

/*
 * GET home page.
 */

 var request = require('reqeust');
 var http = require('http');
 var body = "";

exports.index = function(req, res){

    var options = {
        host: 'api.dev.com',
        port: 80,
        path: '/api/v1/posts',
        method: 'GET'
    };

    request(options, function(err, res, data) { //chunks are already aggregated
      console.log("Got response: " + res.statusCode);
      data = JSON.parse(data); // you need to parse the JSON-string into real object
      console.log(data); // inspect what you got
      res.render('index', { data: data });
    })  
};

确定你需要npm install request,你已经安装了吗?

答案 1 :(得分:0)

data是一个包含对象的数组,请尝试

<%= data[0].title %>