【问题标题】:Apollo fetch cancels on escape key pressApollo fetch 在退出键按下时取消
【发布时间】:2019-02-01 02:00:08
【问题描述】:

我正在使用apollo-client@2.3.5(但这个问题也出现在最新版本上,可能与 Apollo 客户端本身没有直接关系)。

我使用多个请求来加载应用程序的不同部分。我的问题是Escape 按键取消了获取请求,并破坏了整个应用程序。我已经试过了:

  • 捕获Escape keydown 事件并调用preventDefault()stopPropagation()return false
  • 从获取请求选项中删除 signal 字段
  • 在 Apollo 客户端中覆盖 fetch 以使用 axios(但这是不可能的,因为 axios 与 Fetch API 不兼容)

但在Escape 按键上仍会取消请求。

是否有任何解决方法或方法来防止提取请求被取消?或者也许有一些与 Fetch API 兼容的客户端不会取消 Escape 按键上的请求?

【问题讨论】:

    标签: javascript fetch apollo-client


    【解决方案1】:

    对于遇到相同或类似问题的任何人,我设法解决了这个问题:

    1. 我创建了以下函数:

      export const makeRequest = (url, requestParams) => {
          requestParams.data = requestParams.body;
      
          return axios(url, requestParams)
              .then(response => {
                  return new Response(JSON.stringify(response.data), {
                      ...response.headers,
                      status: response.status,
                      statusText: response.statusText
                  })
              });
      };
      
    2. 我在 Apollo Client 中使用 fetch 属性替换了 Apollo Link 中的默认获取:

      new HttpLink({
          uri: config.graphqlUrl,
          credentials: 'same-origin',
          fetch: makeRequest
      })
      

    makeRequest 功能模仿fetch,但不会被Escape 按键取消。

    Apollo 客户端期望响应是 Response 的实例,因此我们为其提供一个。

    编辑: 事实证明,它在 IE11 上不起作用。如果您关心 IE 兼容性,您应该安装 whatwg-fetch (https://www.npmjs.com/package/whatwg-fetch) 并在文件顶部包含以下内容:

    import { Response } from "whatwg-fetch";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多