【问题标题】:How can I send multiple HTTP requests to a URL using Axios and stop sending once I receive a response from one of the request?如何使用 Axios 向一个 URL 发送多个 HTTP 请求,并在收到其中一个请求的响应后停止发送?
【发布时间】:2020-11-13 02:10:18
【问题描述】:

我是 javascript 新手,正在尝试编写一个脚本,该脚本将使用 Axios 将多个 HTTP 请求发送到 Web 服务器。服务器的设计方式是它会随机发送响应到请求。现在,我希望脚本在收到一个响应后停止发送请求。我可以写的基本代码是:

while (1) {
    axios.get('http://localhost:8080/ubuntu_default.html', { withCredentials: true }).then(function (response) {
        document.body.innerHTML = generateSuccessHTMLOutput(response);
        break;
        });

    function generateSuccessHTMLOutput(response) {
        return response.data;
    }
}

假设这个 .js 文件将出现在客户端的浏览器中。

【问题讨论】:

  • 如何或什么触发了您从 axios 进行的 api 调用?
  • 客户端首先请求'/index.html',作为响应,服务器发送回带有两个js文件的HTML代码。一个是这个 js 代码,另一个是 axios.min.js(可在 cdn.jsdelivr.net/npm/axios/dist/axios.min.js 获得)。现在客户端检索这两个js文件。在此之后,客户端请求“localhost:8080/ubuntu_default.html”。为此,服务器会随机向其中一个请求发送响应。
  • 您的代码中没有任何内容表明它被多次触发。如果你有某种循环,分享它也很重要
  • 请编辑您的问题并添加所有相关信息。这很难阅读/调试
  • @Evert 现在编辑了问题中的基本代码..

标签: javascript node.js http web axios


【解决方案1】:

编辑:基于this comment op 只想轮询端点并在收到响应后停止。

示例代码:

(async() { 
    let r = await poll('http://localhost:8080/ubuntu_default.html');
    console.log(r); 
})();

async function poll(endpoint) {
    let countOfError = 0;
    const maxErrors = 10;
    let resp = null;

    while (true) {
        try {
            resp = await axios.get(endpoint, { withCredentials: true }));
            
            //check if resp is "success" then break;    
            //What does a successful response look like?
            if (resp.data.success) break;            
        } catch (e) {
            //console.error(e);  optional
            countOfErrors += 1;
            if (countOfErrors > maxErrors) break;
        }
    }

    return resp;
}

旧答案

你可以使用类似Promise.race

let promises = [];

for (let i = 0; i<10; i++)
   promises.push(
     axios.get('http://localhost:8080/ubuntu_default.html', 
               { withCredentials: true }));

Promise.race(promises).then( generateSuccessHTMLOutput ); 
//Called with whichever promise fulfills first

【讨论】:

  • 所以我正在使用此代码,但即使在我收到之前发送的请求之一的响应后,脚本仍在发送请求:let promises = []; for (let i = 0; ilocalhost:8080/ubuntu_default.html', { withCredentials: true })); Promise.race(promises).then( function (response) { return response.data });
  • 所有请求都指向同一个页面吗?如果是这样,那么您不需要并行发送...
  • 感谢您的回答。所有请求都在同一页面上。但我不确定如何为此更改此代码。此外,当我运行此代码时,它显示如下错误“错误:意外令牌'{'”
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多