请求.JS和节点.js数据问题

Request.JS and Node.js Data problems

本文关键字:数据 问题 js 节点 JS 请求      更新时间:2023-09-26

我是Node的新手,我正在开发一个使用Request.JS从私有API中提取数据的应用程序。 我需要在我的一个视图中显示数据。 目前,我的一个路由中需要并定义了请求,如下所示:

var models  = require('../models');// Required for sequelize
var express = require('express');// Required for the Express framework
var router = express.Router();
var request = require('request');// For requesting API data
router.get('/', function (req, res) {
        request( // Request from API
        'http://PrivateAPI.com:8080/reports/22?type=0&key=privatekey', 
        function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // Print the return of the api call.
        }
      })
    models.User.findAll({ // $$$-Define User DB call. 
      }).then(function(users) {
    res.render('index', { 
      title: 'Project Insight',
      users: users,
      request: request
    });
  });
})

当它运行时,我可以在控制台中看到数据的输出,但我想知道让它在我的一个视图中显示的最佳方式。 另外,我甚至应该在我的路线中使用它吗? 迷路了,谢谢你的帮助。

首先,当前代码存在一些资源依赖问题,因为来自私有 API 的响应在渲染时可能不可用。我只是将数据库调用和后续操作移动到专用服务请求处理程序。对于实际答案:只需将更多数据传递给渲染操作即可:

router.get('/', function (req, res) {
  request( // Request from API
      'http://PrivateAPI.com:8080/reports/22?type=0&key=privatekey', 
      function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body);
          // response ok, continuing
          models.User.findAll({ // $$$-Define User DB call. 
            }).then(function(users) {
          res.render('index', { 
            title: 'Project Insight',
            users: users,
            request: request,
            body: body // <--
          });
        } else {
          // handle error
        }
      });
});

在您的视图/index.ejs 中,只需使用该变量。

<!DOCTYPE html>
<html>
  ...
  Using <%= body %>, properties are also available if applicable ( <%= body.attr1 %>, <%= body.attr2 %>, ...) 
  ...
</html>