【问题标题】:Axios request within /POST request on ExpressExpress 上 /POST 请求中的 Axios 请求
【发布时间】:2017-12-08 07:01:25
【问题描述】:

如下所示,在我的 server.js 文件中,我有一个 /POST Info 请求,该请求在表单提交时被调用。

我开始对 app.post 和 express 路由之间的区别感到困惑,如果无论如何使用路由会对我的代码有好处。

在 /POST 信息中,我有两个对 2 个不同 API 的 axios 请求,我认为将代码移到其他地方以使其更清晰是明智的。

知道这里的路线如何运作对我有好处吗?如果你能解释一下这里的区别,那就太好了。

app.post('/Info', function (req, res) {
   var State = req.body.State;
   var income = Number(req.body.income);
   var zip = req.body.ZIP;
   axios.post('https://taxee.io/api/v2/calculate/2017', {
      //data sent to Taxee.io
      "exemptions": 1
      , "filing_status": "single"
      , "pay_periods": 1
      , "pay_rate": income || 100000
      , "state": State || "NY"
   }, {
         headers: {
            'Authorization': "Bearer <API_KEY>"
            //headers
         }
   }).then(function (response) {
      var obj = {
        income: '$' + income
        , fica: response.data.annual.fica.amount
        , federal: response.data.annual.federal.amount
        , residence: State + ", " + zip
        , state: response.data.annual.state.amount
      }
      axios.get("https://www.quandl.com/api/v3/datasets/ZILL/Z" + zip + "_RMP.json?api_key=<API_KEY>").then(function (response) {
         var monthRent = response.data.dataset.data[0][1]
         obj.rent = monthRent
         obj.yearlyRent = Number(monthRent) * 12;
      }).then(function (response) {
         res.send(obj);
      });
  }).catch(function (error) {
      alert('error');
  });
}

【问题讨论】:

    标签: node.js express routes axios


    【解决方案1】:

    在 Express 应用程序中定义路由有两种方式:

    直接使用 Express 应用程序 (app) 对象:

    const express = require('express')
    const app = express()
    
    app.post(...)
    app.get(...)
    app.put(...)
    // and so on
    

    或者使用router 对象:

    const express = require('express')
    const app = express()
    const router = express.Router()
    
    router.post(...)
    router.get(...)
    router.put(...)
    // and so on
    
    app.use(router)
    

    我的猜测是,您一直在阅读关于 router 对象的后一个 sn-p 代码。使用 Express 的 Router 对象确实可以使代码更清晰,因为更多的关注点分离。

    从您自己的 API 调用外部 API 没有任何问题。例如,在我的一个项目中,我在 this 行调用 Google Calendar API。我和你的唯一区别是我使用了Google APIs Node.js Client,而你使用了标准的 HTTP 请求。我当然可以使用here 所示的 HTTP 请求。

    您的代码很好,但可以改进。例如,而不是:

    axios.post('...', {
      exemptions: 1,
      filing_status: 'single',
      pay_periods: 1,
      pay_rate: income || 100000,
      state: State || 'NY'
    })
    

    你可以调用一个辅助函数来准备选项对象:

    function prepareOptions (state = 'NY', income = 100000) {
      return {
        exemptions: 1,
        filing_status: 'single',
        pay_periods: 1,
        pay_rate: income,
        state: State
      }
    }
    

    然后这样称呼它:

    axios.post('...', prepareOptions(State, income))
    

    这使得代码更具可读性。

    最后,没有理由在服务器端使用 axios。只需使用 Node 内置的HTTP module

    【讨论】:

    • http.get({ hostname: 'localhost', port: 80, path: '/', agent: false // 只为这个请求创建一个新代理 }, (res) => { // 用响应做事 });像这样没有代理?
    【解决方案2】:
        app.post('/Info', function (req, res) {
    
            var uData ={
                 state: req.body.State,
                income : Number(req.body.income),
                zip: req.body.ZIP
            };
    
            taxee(uData).then(function(data){
    
              return rent(data)  ;
            }).then(function(fullData){
    
                res.send(fullData);
            }).catch(function (error) {
            res.render('error');
        });
    function taxee(data) {
        return new Promise((resolve, reject) => {
    
            var income = data.income;
            var state = data.state;
            var zip = data.zip;
            axios.post('https://taxee.io/api/v2/calculate/2017', {
                //data sent to Taxee.io
                "exemptions": 1
                , "filing_status": "single"
                , "pay_periods": 1
                , "pay_rate": income || 100000
                , "state": state || "NY"
            , }, header).then(function (response) {
                var taxData = {
                    income: '$' + income
                    , fica: response.data.annual.fica.amount
                    , federal: response.data.annual.federal.amount
                    , stateTax: response.data.annual.state.amount
                    , state
                    , zip: zip
                }
                resolve(taxData);
            }).catch(function (error) {
                console.log('break');
                resolve(error);
            });
        });
    };
    
    function rent(data) {
        return new Promise((resolve, reject) => {
            axios.get("https://www.quandl.com/api/v3/datasets/ZILL/Z" + data.zip + "_RMP.json?api_key=d7xQahcKCtWUC4CM1LVd").then(function (response) {
                console.log(response.status, ' status');
                var monthRent = response.data.dataset.data[0][1];
                data.rent = monthRent
                data.yearlyRent = Number(monthRent) * 12;
                return data;
            }).then(function (response) {
                resolve( data);
            }).catch(function (error) {
                reject(error);
            });
        });
    }
    module.exports = {
        taxee
        , rent
    };    
    

    最终将上面的代码放入干净的 promise 方法中。真的很高兴结果如何!

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2019-07-23
      • 2016-09-29
      • 1970-01-01
      • 2019-11-04
      • 2019-06-26
      • 2021-02-04
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多