【问题标题】:Axios: Using and passing response variables to middleware route functionsAxios:使用响应变量并将其传递给中间件路由函数
【发布时间】:2018-09-19 02:56:07
【问题描述】:

我有一个用 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】:

    在这段代码中:

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

    干杯,

    【讨论】:

    • 嗯是的,也许,然后我可以将前两个 axios 请求的结果传递给我的函数回调,然后做我想做的事。但是,我不确定是否可以将结果作为 ${data...} 之类的 url 参数传递。通常,我会使用 next() 在 Node 中传递数据,然后使用回调转到下一个路由控制器函数,然后使用 res.locals.someData 检索值...我在 axios 中找不到关于等效事物的文档.. 通常,一个人在请求正文中传递数据,而不是在 url-string 中传递数据?
    • @MMM 我不确定我是否遵循。这取决于您的请求/api。如果您发出 GET 请求,参数通常以以下形式通过 URL 传递(对于 REST API):/users/{userNumber}。虽然,如果它是一个 POST 请求,那么是的,你的请求的主体很可能是一些 JSON 数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2019-08-06
    • 2020-10-23
    • 1970-01-01
    • 2018-12-14
    • 2016-05-26
    相关资源
    最近更新 更多