【问题标题】:Timeout feature in Axios has no effect in a NativeScript(-Vue) environmentAxios 中的超时功能在 NativeScript(-Vue) 环境中无效
【发布时间】:2019-11-08 13:40:50
【问题描述】:

我有一个使用 axios 库使用 vue init nativescript-vue/vue-cli-template 构建的 Nativescript-Vue 项目。

如果我在浏览器环境中运行以下sn-p,它可以正常工作,即在如此短的超时设置下按预期超时:

    const apiClient = axios.create({
      timeout: 1,
    })

    apiClient.request({
      url: 'https://jsonplaceholder.typicode.com/todos/1',
    }).then(response => {
      console.log('this.apiClient.defaults.timeout', apiClient.defaults.timeout)
      console.log(response.config)
      console.log(response.data)
    }).catch(e => {
      console.log(e)
    })

但是,当我在 Android 上的 NativeScript-Vue 项目中运行代码时,请求完成,就好像根本没有超时设置一样。即使您可以从 console.logs 中看到 timeout 的值为 1。

如果我使用 NativeScript 的“http/http-request”模块发出类似的请求,超时设置会按预期得到遵守。

[更新:]

事实证明,仅以下 Manoj 的解决方法不足以满足我们的要求,因为仅在 org.nativescript.widgets.Async's HttpRequestTask 中为 HttpURLConnection 设置了连接超时。设置读取超时提供了预期的结果,即在超时期限内没有接收到数据时导致超时到期。所以,I suggested 考虑在连接超时之外设置读取超时:

// apply timeout
if (options.timeout > 0)
{
  connection.setConnectTimeout(options.timeout);
  connection.setReadTimeout(options.timeout);
}

【问题讨论】:

  • 响应中有哪些值? catch 没有被调用?
  • 响应数据只是一个简单的对象,例如。 { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } 是的,catch 没有被调用,因为请求成功而不是超时。

标签: android axios nativescript


【解决方案1】:

我猜它没有在 XHR 包装器中实现(从 v6.2.0 开始),而只是在原始的 http 请求类中实现。尝试在您的app.js 中添加以下代码。

import { XMLHttpRequest } from 'tns-core-modules/xhr';
import * as types from "tns-core-modules/utils/types";

XMLHttpRequest.prototype.originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (data) {
    if (types.isDefined(this._options) && types.isNumber(this.timeout)) {
        this._options.timeout = this.timeout;
    }
    this.originalSend(data);
};

您可能想在 Github 上提交问题。

【讨论】:

  • 尝试添加您的建议。该函数被调用,但 this.timeoutundefined
  • timeout 只有在 Axios 上设置才有效。如果您有问题,请分享 Playground 示例进行测试。
  • 这里是游乐场play.nativescript.org/?template=play-vue&id=hAc6cD 感谢您的帮助!
  • axios 在调用 open 方法后设置超时。因此覆盖了似乎可以完成这项工作的发送方法。 Updated Playground
猜你喜欢
  • 1970-01-01
  • 2019-09-06
  • 2016-08-09
  • 2019-10-25
  • 2020-12-26
  • 1970-01-01
  • 2019-12-06
  • 2020-08-19
  • 2020-05-10
相关资源
最近更新 更多