我正在循环一个字符串数组,并希望将这些字符串以 30 个为一组作为查询参数传递到 axios GET 请求中,但我不知道如何正确执行。
const ids = ["1","2", "3", "4", "5"] //最多 10K 条目
我需要的是 30 个 id 作为查询参数,每个请求都具有相同的键,如下所示
axios.get("/endpoint?id=1&id=2&id=3&id=4") 等等。我的方法不起作用,我欢迎一些有关如何正确处理此问题的提示。
我拥有的
const assets = await getRepository(Asset).find({ collection: collection })
const token_ids = assets.map(a => {
return a.token_id
})
const asset_count = assets.length;
let config: AxiosRequestConfig = {
headers: this.header,
params: {
limit: 50,
offset: 0,
side: 1,
sale_kind: 0,
order_by: "eth_price",
order_direction: "asc",
asset_contract_address: assets[0].asset_contract.address
}
}
while (true) {
const ids = token_ids.splice(0,30); //get 30 ids for pagination (max)
//apply ids to params
for( let i=0; i< ids.length; i++){
config.params["id"] = ids[i]; //this wont work cause duplicate keys arent allows
}
const response = await axios.get(this.API_BASE_URL + "/orders", config)
//do something
}Run Code Online (Sandbox Code Playgroud)
我发现这个方法似乎可以发送正确的网址。
paramsSerializer在配置中添加一个方法将处理发送的所有参数。那么您所需要的只是处理这些值(如果它们是数组格式)的逻辑。
使用该方法显示的urlPathresponse.request.path如下:
/orders?limit=50&offset=0&side=1&sale_kind=0&order_by=eth_price&order_direction=asc&id=1&id=2&id=3&id=4&id=5
我不确定为什么您的请求在 while 循环中发送,但如果您需要,只需将其添加回来即可。
const assets = await getRepository(Asset).find({ collection: collection })
const token_ids = assets.map(a => {
return a.token_id
})
const asset_count = assets.length;
let config: AxiosRequestConfig = {
headers: this.header,
params: {
limit: 50,
offset: 0,
side: 1,
sale_kind: 0,
order_by: "eth_price",
order_direction: "asc",
asset_contract_address: assets[0].asset_contract.address
},
paramsSerializer: function handleQuery(query) { // this will process params
// This should query the params properly for you.
return Object.entries(query).map(([key, value], i) => Array.isArray(value) ? `${key}=${value.join('&' + key + '=')}` : `${key}=${value}`).join('&');
}
}
// put the ids all into a id array into the config.params object.
config.params.id = token_ids.splice(0, 30);
const response = await axios.get(this.API_BASE_URL + "/orders", config)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2888 次 |
| 最近记录: |