0

I have been trying to learn the MEAN stack and ran into some issues with the javascript below that is in node.js. I have been having trouble with my module.exports.homelist function in which the functions, like function (err, response, body), have been giving me those values as undefined. I have been searching for answers for a while and came across asynchronous code and the callback function, but I was unable to find the solution that fits my situation, especially when the function is called on from within a request.

The Code:

var request = require('request');
var apiOptions = {
    server : "https://localhost:3000"
};
if (process.env.NODE_ENV === 'production') {
    apiOptions.server = "https://getting-mean-loc8r.herokuapp.com";
}

var renderHomepage = function (req, res, responseBody) {
    var message;
    if (!(responseBody instanceof Array)) {
        message = "API lookup error";
        responseBody = [];
    } else {
        if (!responseBody.length) {
            message = "No places found nearby";
        }
    }
    res.render('locations-list', {
        title: 'Loc8r - find a place to work with wifi',
        pageHeader: {
            title: 'Loc8r',
            strapline: 'Find places to work with wifi near you!'
        },
        sidebar: "Looking for wifi and a seat? Loc8r helps you find places to work when out and about. Perhaps with coffee, cake or a pint? Let Loc8r help you find the place you're looking for.",
        locations: responseBody,
        message: message
    });
}

/* GET 'home' page */
module.exports.homelist = function(req, res) {
    var requestOptions, path;
    path = '/api/locations';
    requestOptions = {
        url : apiOptions.server + path,
        method : "GET",
        json : {},
        qs : {
            lng : -0.7992599,
            lat : 51.378091,
            maxDistance : 20
        }
    };
    request(
        requestOptions,
        function(err, response, body) {
            var i, data;
            data = body;
            if (data !== undefined && response !== undefined && response.statusCode === 200 && data.length) {
                for (i=0; i<data.length; i++) {
                    data[i].distance = _formatDistance(data[i].distance);
                }
            }
            renderHomepage(req, res, data);
        }
    );

    var _formatDistance = function (distance) {
        var numDistance, unit;
        if (distance > 1) {
            numDistance = parseFloat(distance).toFixed(1);
            unit = 'km';
        } else {
            numDistance = parseInt(distance * 1000,10);
            unit = 'm';
        }
        return numDistance + unit;
    }
};

EDIT: This is the code I have in another file that uses my homelist function to render an HTML homepage:

var express = require('express'); var router = express.Router(); 
var ctrlLocations = require('../controllers/locations');
router.get('/', ctrlLocations.homelist);
module.exports = router;
  • How is this module loaded and called? We need to see how `.homeList(...)` is called and what you'[re doing in the callback when it is called. – jfriend00 Jul 19 '16 at 00:37
  • Oh sorry the callback was just testing something out from what I had seen on stack overflow for people running into the same problem, but of course it's a bad idea to do a callback within a request function, so just ignore the callback for now. I'm using a book called "Getting Mean" by Simon Holmes to do this project, in which I have another file that requires this file above and then uses the router.get function to use the homelist function. – Shivan Vipani Jul 19 '16 at 18:23
  • This is the code for the use of the above file: var express = require('express'); var router = express.Router(); var ctrlLocations = require('../controllers/locations'); router.get('/', ctrlLocations.homelist); module.exports = router; – Shivan Vipani Jul 19 '16 at 18:24
  • please put the code into your question to make it readable. – jfriend00 Jul 19 '16 at 18:32
  • The callback you have in `.homelist` is a problem. As a request handler, the third parameter is the `next()` callback and if you call that with a non-null value, express thinks you have an error. That doesn't explain your issue with `request()`, but it's definitely the wrong way to code an express request handler. – jfriend00 Jul 19 '16 at 19:39
  • So I removed the callback just to make my code a little cleaner (since I was just testing something out and had forgotten to remove it). What do you think my main problem is in the code? From what I have seen in my console whenever I check the parameter err from the function that was in the request function, it says I have a socket hang up, if that is any help for you. I know a socket hang up is a little related to a timeout error, but I'm not to sure where to go from here. – Shivan Vipani Jul 19 '16 at 22:59
  • What is the EXACT error you get (word for word)? – jfriend00 Jul 19 '16 at 23:16
  • This was the output in the log: { [Error: socket hang up] code: 'ECONNRESET' } – Shivan Vipani Jul 20 '16 at 04:56
  • See [node.js ECONNRESET](http://stackoverflow.com/a/17637900/816620). This means that the other end is abruptly closing/losing the socket connection. – jfriend00 Jul 20 '16 at 05:00

1 Answers1

0

You mention MEAN stack- are you requiring express? Please read the documentation on the express website.

gcoreb
  • 181
  • 5
  • Yeah I am. I've got other files that take care of requiring all of the packages I need. I just didn't want to waste people's time reading through the rest of the files since I was able to narrow down my coding issue to this specific file. – Shivan Vipani Jul 19 '16 at 01:14