【问题标题】:How to get data from custom created function in JS using https node module如何使用 https 节点模块从 JS 中自定义创建的函数中获取数据
【发布时间】:2022-07-10 01:38:34
【问题描述】:

如何使用 HTTPS/HTTP 节点模块从我的函数 getDashboardData() 而不是 JSON PLACE HOLDER 模拟 API 获取数据,以及如何使这个获取数据 HTTP/HTTPS 模块的端点像 Angular 一样在前端利用响应?

我的模拟 backen.js 文件:

const https = require('https');
 
https.get(getDashboardData.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 getDashboardData() {
  var data = {};
 
  var dashboard1 = {};
  dashboard1.orders = 10;
  dashboard1.lastVisit = 70;
   dashboard1.revenue = 70;
   dashboard1.lastWeek = 70;
   dashboard1.customers = 70;
   dashboard1.newlyRegistered = 70;
   dashboard1.comments = 70;
   dashboard1.responded = 70;
   dashboard1.storedAt = "2022/15/5 5:01:30";
   data.dashboardData = [];
   data.dashboardData.push(dashboard1);
   return data;
 }

您的时间和帮助将不胜感激。谢谢:)

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    万岁!我在 node js 中使用以下代码和 Express 得到了它。我只是将创建数据的自定义方法称为快速“获取”端点。当我到达终点时,响应将是我的自定义方法结果。

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

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2021-05-25
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多