简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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