node.js / express链接多个get命令

时间:2015-04-19 08:08:38

标签: javascript node.js express

我有一条路线我为了获得所有数据需要多次访问API服务器(根据给出的数据)。

现在我需要添加第三次访问服务器,它变得相当难以理解 以下代码正在运行,但我感觉我做得不对(承诺?) - 无法弄清楚在这种情况下究竟推荐什么

代码:(剥离以强调要点)

router.get('/', function(req, main_response) {
        http.get(FIRST_API_COMMAND, function (res) {
            var moment_respose_content = '';
            res.on("data", function (chunk) {
                moment_respose_content += chunk;
            });
            res.on('end',function(){
                if (res.statusCode < 200 || res.statusCode > 299) {
                    main_response.send('error in getting moment');
                    return;
                }
                var response = JSON.parse(moment_respose_content );
                if (response.success)
                {
                    var data = response.data;
                    //doing something with the data
                    http.get(SECOND_API_COMMAND, function (res) {
                        res.on("data", function (chunk) {
                            comment_respose_content += chunk;
                        });

                        res.on('end',function(){
                            var response = JSON.parse(comment_respose_content);
                            if (response.success)
                            {
                                var comments = response.data;
                                main_response.render('the page', {data: data});
                                return;
                            }
                        });
                    }).on('error', function (e) {
                        console.log("Got error: " + e.message);
                        main_response.send('Error in getting comments');
                    });
                    return;
                }
            });
        }).on('error', function (e) {
            console.log("Got error: " + e.message);
            main_response.send('Error in getting moment');
        });
});

1 个答案:

答案 0 :(得分:2)

您可以为每个远程操作编写中间件,然后在use处理程序之前get编写这些中间件,以便get处理程序可以简单地访问其结果。 (如果您需要在等待较早的请求之前启动后续请求,Promise可以提供帮助,但这种情况很少见。)

例如,使用express中间件独立获取每个远程数据:

var request = require('request');
var express = require('express');
var app = express();
var router = express.Router();

/* middleware to fetch moment. will only run for requests that `router` handles. */
router.use(function(req, res, next){
    var api_url = 'https://google.com/';
    request.get(api_url, function(err, response, body) {
        if (err) {
            return next(err);
        }
        req.moment_response = response.headers["date"];
        next();
    });
});

/* middleware to fetch comment after moment has been fetched */
router.use(function(req, res, next){
    var api_url = 'https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new';
    request.get(api_url, function(err, response, body){
        if (err) {
            return next(err);
        }
        req.comment_response = parseInt(body);
        next();
    });
});

/* main get handler: expects data to already be loaded */
router.get('/', function(req, res){
    res.json({
        moment: req.moment_response,
        comment: req.comment_response
    });
});

/* error handler: will run if any middleware called next() with an argument */
router.use(function(error, req, res, next){
    res.status(500);
    res.send("Error: " + error.toString());
});

app.use('/endpoint', router);

app.listen(8000);

通常,您要获取的远程数据基于主请求的某些参数。在这种情况下,您可能希望使用req.param()而不是App.use()来定义数据加载中间件。