简体   繁体   中英

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");
  });
});

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM