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

问题描述 投票:0回答:1

我有一个用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 ]}
            }
        },
        {...}

然后,我的第三个路由器链接返回前两个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将res.locals值从2个路由器链接传递到第三个链接?在Express中,我只是通过使用next()函数来做到这一点......

node.js express axios middleware
1个回答
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
        });
    }

干杯,

© www.soinside.com 2019 - 2024. All rights reserved.