s4tr2
s4tr2

Reputation: 415

Getting data in JSON format from an API using express and nodejs

I am trying to get the analytics data from an API using expressjs. The data is in JSON format. The point is that I want to display the result in the view. I am able to get the data in the console, but I am not able to do that in the view.

Here is what I have tried so far:

app.js

var express = require('express');
var http = require('http');
var app = express();
var request = require('request');
http.get('http://localhost:8383/analytics/piwik/index.php?module=API&method=Actions.getPageUrls&idSite=1&date=yesterday&period=day&format=json&filter_limit=10', function(res){
  var body = "";
  res.on('data', function(chunk){
      body += chunk;
  });
  res.on('end', function(){
    var resp = JSON.parse(body);
    console.log(resp);
  });
  app.listen(3000, function(){
    console.log("Example app listening to port 3000");
  });
});

Upvotes: 1

Views: 2156

Answers (2)

Ajay Mewada
Ajay Mewada

Reputation: 1

After getting response you will have to render the data see example below:-

 var resp = {
        'name':'demoUsername',
        'contact': '+91-9876543210'
    }
    res.render('index', { resp: resp });

I am using EJS template engine see the code below:-

<html>
<body>
  <table>
    <tr>
      <td>Name</td>
      <td>Contact</td>
    </tr>
    <tr>
      <td><%= resp.name%></td>
      <td><%= resp.contact%></td>
    </tr>
  </table>
</body>
</html>

Upvotes: 0

Shadi Altarsha
Shadi Altarsha

Reputation: 133

You have two options to do that: 1-you can use a tempting language for rendering the data in your app like handlebars or mustache of ejs and so many other chooses. 2- you can make an endpoint and make your client connects to it using ajax and then render the data using javascript (frameworks can help here)

Upvotes: 2

Related Questions