简体   繁体   English

Request.JS和Node.js数据问题

[英]Request.JS and Node.js Data problems

I am new to Node and I am developing an app that uses Request.JS to pull data from a private API. 我是Node的新手,正在开发一个使用Request.JS从私有API提取数据的应用程序。 I need the data to be displayed in one of my views. 我需要将数据显示在我的一个视图中。 Currently I have Request being required and defined in one of my routes, like so: 目前,在我的一条路线中,我已要求并定义了请求,如下所示:

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

When this runs, I can see the output of the data in my console, but I wanted to know the best way to have it display in one of my views. 当它运行时,我可以在控制台中看到数据的输出,但是我想知道在我的一个视图中显示数据的最佳方法。 Also, should I even have this in my route? 另外,我该在路线上放这个吗? Am lost, thanks for any help. 迷路了,谢谢您的帮助。

First of all, the current code has some resource dependency issues, since the response from the private API might not be available at the time of render. 首先,当前代码存在一些资源依赖问题,因为专用API的响应在渲染时可能不可用。 I have simply moved the database call and succeeding operations to the private service request handler. 我只是简单地将数据库调用和后续操作移到了私有服务请求处理程序。 For the actual answer: it's as simple as passing more data to the rendering operation: 对于实际的答案:这就像将更多数据传递给渲染操作一样简单:

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

In your view/index.ejs, simply use the variable. 在您的view / index.ejs中,只需使用变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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