Axios:使用响应变量并将其传递给中间件路由函数

时间:2018-09-17 11:45:20

标签: node.js express axios middleware

我有一个使用Axios实现的中间件:它调用2或3条路由,前2条路由函数使用res.locals.someVariable和next()函数返回单个值,例如:

exports.getReservierungenByMonth = function(req,res,next) {

        Produkt.aggregate([
            {
                "$unwind":"$DemonstratorWerte"
            },
            {   
                "$match": {"DemonstratorWerte.Demonstrator" : +req.params.demo_id/*, "ProduktReserviert.Status": false*/}
            },

            .......
            {
                "$addFields": { 
                    "Monat": { 
                        "$let":  { 
                            "vars": {  
                                "monthsInStrings": [, "Januar", "Februar", "Maerz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"] 
                            }, 
                            "in": {  
                                "$arrayElemAt": ['$$monthsInStrings','$Monat'] 
                            } 
                        } 
                    } 
                } 
            }
        ]).exec(function(err, prod) {
                if (err) {
                        res.json(err);
                    }

                else {                  
                    res.locals.reservierungen = reservierungenArray;
                    //res.locals.reservierungen = prod;
                    next();
                }
            })//.then((res) => res.json())
        };

然后,我来自axios的第三个路由器链接使用这些res.locals变量来查询和汇总一些数据,例如:

exports.getStornierungenReservierungen = function(req,res,next) {

    stornierungen = res.locals.stornierungen;
    reservierungen = res.locals.reservierungen; 

    Produkt.aggregate([ 
        {
            $project: {
            "Alle": { $concatArrays: [ stornierungen, reservierungen ]}
            }
        },
        {...}

然后,我的第三个路由器链接返回来自2个先前的res.locals值的聚合数据,包括最后一个路由函数:

router.route('/Middleware/sdasdhgrt/:demo_id').get(function(req,res,next) {
    axios.all([
      axios.get(`http://localhost:2323/D/L4C/a/${req.params.demo_id}`),
      axios.get(`http://localhost:23325/D/Ls/b/${req.params.demo_id}`),
      //axios.get(`http://localhost:53355/4Z/L4C/3/${req.params.demo_id}`)--->> needs the res.locals values!
    ])
    .then(axios.spread(function (result1,result2,result3) {
      res.send({result1,result2});
      res.write(JSON.stringify({
        result1, result2, result3
      }));
      //console.log('Result1: ', result1.data);
      //console.log('Result2: ', result2.data);
      //console.log('Result3: ', result3.data);
    })).catch(error => {
      console.log(error);
    }); 
    });

我现在的问题是:如何使用axios将2个路由器链接中的res.locals值传递给第三个链接?在Express中,我只是通过使用next()函数来完成此操作的。

1 个答案:

答案 0 :(得分:0)

在此代码中:

axios.all([
  axios.get(`http://localhost:2323/D/L4C/a/${req.params.demo_id}`),
  axios.get(`http://localhost:23325/D/Ls/b/${req.params.demo_id}`),
  //axios.get(`http://localhost:53355/4Z/L4C/3/${req.params.demo_id}`)--->> needs the res.locals values!
])

您是否不能仅将前两个请求用作axios.all()的一部分,然后使用.then(callback)发出第三个请求?像这样:

axios.all([
  axios.get(`http://localhost:2323/D/L4C/a/${req.params.demo_id}`),
  axios.get(`http://localhost:23325/D/Ls/b/${req.params.demo_id}`),
])
.then((done) => { 
 axios.get(`http://localhost:53355/4Z/L4C/3/${req.params.demo_id}`)
 done();
})
.then((done) => {
  //the rest of your code
  done();
})

编辑:

老实说,我也只使用async / await这样的东西(可能会丢失一些东西,我根本没有测试,只是把它写在脑海中):

try {
        let dataToUse = [], promises = [];
        let now = new moment();
        promises.push(axios(`http://localhost:2323/D/L4C/a/${req.params.demo_id}`));
        promises.push(axios(`http://localhost:23325/D/Ls/b/${req.params.demo_id}`));

        const responses = await Promise.all(promises);
        dataToUse = responses.map(response => response.data);
        //make third request with data
        axios.get(`http://localhost:53355/4Z/L4C/3/${dataToUse.parameter}`);

        // Send your data with res.send();
    } catch (e) {
        res.status(400).send({
            //error info
        });
    }

干杯