0

我试图开发一个基于 node.js 的 Web 应用程序,它与 PHP api 交互。下面我尝试请求我的 PHP api 创建的 JSON 对象。我要做的就是获取它,然后在我的 .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"}]
4

2 回答 2

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,您已经安装了吗?

于 2013-01-16T20:23:51.197 回答
0

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

<%= data[0].title %>
于 2013-01-16T13:31:09.450 回答