簡體   English   中英

Nodejs:如何使用 async/await 處理 http 請求節流錯誤?

[英]Nodejs: How to handle http request throttle error using async/await?

我正在嘗試構建一個搜索 API,它將位置作為參數並返回該位置的緯度和經度。 我正在使用http://geocode.xyz來獲取位置的詳細信息。 例如: https : //geocode.xyz/?locate=Warsaw,Poland&json=1這將返回該位置所需的緯度和經度。

這是我擁有的代碼片段:

const url = 'https://geocode.xyz/?locate=Warsaw,Poland&json=1';
const getData = async url => {
try {
  const response = await fetch(url);
  const json = await response.json();
  console.log(json);
} catch (error) {
  console.log(error);
}
};
getData(url);

有了這個,這是我看到的錯誤:

node geocode.js
{success: false, error: { code: '006', message: 'Request Throttled.'}}

我猜這個錯誤是因為我需要限制訪問 API https://geocode.xyz的請求數量。 我不確定如何在異步/等待中使用速率限制器。 任何幫助,將不勝感激。

編輯:根據下面的答案,我仍然看到“請求限制”

var request = require('request');
const fetch = require("node-fetch");

const requester = {
    lastRequest: new Date(),
    makeRequest: async function(url) {
        // first check when last request was made
        var timeSinceLast = (new Date()).getTime() - this.lastRequest.getTime();
        if (timeSinceLast < 2000) {
            this.lastRequest = new Date(this.lastRequest.getTime() + (2000 - timeSinceLast));
            await new Promise(resolve => setTimeout(resolve, 2000-timeSinceLast));
          //  await new Promise(resolve => setTimeout(resolve, timeSinceLast));
        }
        const response = await fetch(url);
        const json = await response.json();
        return json;
    }
};
requester.makeRequest('https://geocode.xyz/?locate=Warsaw,Poland&json=1')
.then(console.log)

我仍然遇到同樣的錯誤:

{ success: false, error: { code: '006', message: 'Request Throttled.' } }

這是因為地理編碼定價嗎? 有沒有辦法限制用戶端的請求率?

您可以創建一個用於發送所有請求的對象,並且該對象可以跟蹤上次發出請求的時間。 例如

const requester = {
    lastRequest: new Date(2000,0,1),
    makeRequest: async function (url) {
        // first check when last request was made
        var timeSinceLast = (new Date()).getTime() - this.lastRequest.getTime();
        this.lastRequest = new Date();
        if (timeSinceLast < 1000) {
            this.lastRequest = new Date(this.lastRequest.getTime() + (1000 - timeSinceLast));
            await new Promise(resolve => setTimeout(resolve, 1000-timeSinceLast));
        }

        // make request here and return result
        const response = await fetch(url);
        const json = await response.json();
        return json;
    }
};

https://jsfiddle.net/3k7b0grd/

如果您使用requester.request ,它只允許您每秒發出一次請求,並等待足夠長的時間(即使是連續請求)以遵守該速率限制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM