http.get and node.js and JSON


http.get and node.js and JSON

我试图开发一个基于node.js与PHP api交互的web应用程序。下面我尝试请求一个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 %>
然而

数据。title返回undefined,我的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"}]

尝试使用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,你已经安装了吗?

data是一个包含对象的数组,try

<%= data[0].title %>