Node.js:REST调用和请求函数返回未定义的值

时间:2016-07-19 00:30:32

标签: javascript node.js request undefined

我一直在尝试学习MEAN堆栈并遇到了node.js下面的javascript的一些问题。我的module.exports.homelist函数遇到了问题,其中函数(如函数,错误,响应,正文)一直在给我这些未定义的值。我一直在寻找答案并遇到异步代码和回调函数,但我无法找到适合我情况的解决方案,尤其是在请求中调用该函数时。

守则:

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

编辑:这是我在另一个文件中使用我的homelist函数呈现HTML主页的代码:

var express = require('express'); var router = express.Router(); 
var ctrlLocations = require('../controllers/locations');
router.get('/', ctrlLocations.homelist);
module.exports = router;

1 个答案:

答案 0 :(得分:0)

你提到MEAN堆栈 - 你需要快递吗?请阅读快递网站上的文档。