gpt4 book ai didi

node.js - axios 内请求/Express 上的 POST 请求

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:25 25 4
gpt4 key购买 nike

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

在阅读 app.post 和 Express 路线之间的差异时,我开始感到困惑,以及无论如何使用路线是否会对我的代码有利。

在/POST Info 中,我对 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');
});
}

最佳答案

在 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 对象的后一段代码。使用 express 'Router对象确实可以使代码更清晰易读,因为有更多的关注点分离。

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

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

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 .

关于node.js - axios 内请求/Express 上的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com