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:
JavaScript
x
32
32
1
const https = require('https');
2
3
https.get(Data.data, res => {
4
let data = [];
5
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
6
console.log('Status Code:', res.statusCode);
7
console.log('Date in Response header:', headerDate);
8
9
res.on('data', chunk => {
10
data.push(chunk);
11
});
12
13
res.on('end', () => {
14
console.log('Response ended: ');
15
const users = JSON.parse(Buffer.concat(data).toString());
16
17
for(user of users) {
18
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
19
}
20
});
21
}).on('error', err => {
22
console.log('Error: ', err.message);
23
});
24
25
26
27
function Data() {
28
var data = {};
29
..
30
return data;
31
}
32
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.
JavaScript
1
24
24
1
const express = require('express');
2
const cors = require('cors');
3
4
const app = express();
5
app.use(cors());
6
7
app.get('/data', (req, res) => {
8
res.send(
9
getDashboardData());
10
});
11
12
app.listen(3000, () => {
13
console.log('server is listening on port 3000');
14
});
15
16
17
18
function Data() {
19
var data = {};
20
.
21
//console.log(JSON.stringify(data));
22
return JSON.stringify(data);
23
}
24