我试图开发一个基于 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"}]