3

I'm new to Node, and Javascript in general. I'm working with the request module to get a JSON response from a web service. I'm not sure if it'd be best to turn my request into a function, or embed the request inside of another function. I haven't had any luck either way.

// Module imports
var express = require('express');
var router = express.Router();
var request = require('request');

var options = {
  url: 'https:www.example.com/wow.json',
  auth: {
    user: 'user',
    password: 'pass',
    json: true
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log(err);
    return;
  }
  requestResult = JSON.parse(body); // All data
  wowUsage = requestResult.publishers[0].used;
});

// Sending data to the template view
router.get('/', function(req, res, next) {
  res.render('template', {tempVar: wowUsage});
});

module.exports = router;

Whenever I start up my web server, this code executes once, and then it's done. Refreshing the page won't load any new information. Should I embed the request in a function, and then call that function in my router.get statement? I tried to nest the request in a function, but I couldn't make that work at all.

1 Answer 1

5

If you put the request in a separate function, make sure to add a callback parameter to the new function that gets called with the appropriate data. For example:

function getJSON(callback) {
  request(options, function(err, res, body) {
    if (err)
      return callback(err);
    try {
      callback(null, JSON.parse(body).publishers[0].used);
    } catch (ex) {
      callback(ex);
    }
  });
}

router.get('/', function(req, res, next) {
  getJSON(function(err, wowUsage) {
    if (err) {
      console.log(err.stack);
      return res.status(500);
    }
    res.render('template', {tempVar: wowUsage});
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.