Skip to content
Advertisement

How to get data from custom created function in JS using https node module

How to get data from my function Data() instead of JSON PLACE HOLDER mock API using HTTPS/HTTP node module and how to make an endpoint of this get data HTTP/HTTPS module to utilize response in front end just like Angular?

My mock backen.js file:

const https = require('https');
 
https.get(Data.data, res => {
  let data = [];
  const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
  console.log('Status Code:', res.statusCode);
  console.log('Date in Response header:', headerDate);

  res.on('data', chunk => {
    data.push(chunk);
  });

  res.on('end', () => {
    console.log('Response ended: ');
    const users = JSON.parse(Buffer.concat(data).toString());

    for(user of users) {
      console.log(`Got user with id: ${user.id}, name: ${user.name}`);
    }
  });
}).on('error', err => {
  console.log('Error: ', err.message);
});



function Data() {
  var data = {};
 ........
   return data;
 }

Your time and help will be really appreciated. Thanks 🙂

Advertisement

Answer

Hurray! I got it using the following code and Express in node js. I simply call my custom method that creates data into an express “get” endpoint. When I hit the end point the response will be my custom method result.

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());

app.get('/data', (req, res) => {
res.send(
  getDashboardData());
});

app.listen(3000, () => {
    console.log('server is listening on port 3000');
});



function Data() {
  var data = {};
  ..........
   //console.log(JSON.stringify(data));
   return JSON.stringify(data);
 }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement