如何从我的node.js服务器获取Json响应并在web(ejs)页面上显示它

时间:2015-01-21 11:45:02

标签: json node.js express ejs

我想知道如何从我的node.js服务器获取json响应并在我的网页上显示响应

下面的

是json代码中的请求和响应

var request = require("request"),
    username = req.body.username,
    password = req.body.password,
    url = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+username+"&pass="+password;


    console.log("url is "+url);
    request.get(
    {
        url : url
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
       if (!error && response.statusCode == 200) {
        var json_body = JSON.parse(body);
        console.log(json_body); 
        var msg = json_body.profile.user;//this is the message i want to show on my web page(msg)
    console.log(msg); // get json response
  }
    }
);

1 个答案:

答案 0 :(得分:1)

您首先必须注册express才能使用ejs:

app.engine('.html', require('ejs').__express);

然后您可以使用res.render并将数据传递给视图

res.render('index.html', {msg: json_body.profile.user});

之后,您可以通过EJS

访问它
<%= msg %>

如果您需要一个有效的例子,可以在以下网址找到一个好的例子:

https://github.com/strongloop/express/tree/master/examples/ejs