【问题标题】:Axios 'mode' does not exist in type 'AxiosRequestConfig''AxiosRequestConfig' 类型中不存在 Axios 'mode'
【发布时间】:2021-01-26 19:35:47
【问题描述】:
描述错误

我正在尝试发出要求将模式设置为no-cors 的请求。但是,我无法将 mode 传递到 Axios 配置中。我收到 TypeScript 错误 Object literal may only specify known properties, and 'mode' does not exist in type 'AxiosRequestConfig'

最终,我需要能够在sec-fetch-mode: no-cors 存在的地方提出请求。

const client: AxiosInstance = axios.create({
  baseURL: apiBaseUrl,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
  adapter: cache.adapter,
});

无论是通过mode 还是其他财产,我都需要一种方法来提出这个请求。

重现
const mediaUrl: string = await client
  .get(paths.moment.media.getMediaUrl({ mediaId: media.id }), {
    mode: 'no-cors'
  })
.then(({ data }: { data: string }): string => data);
预期行为

能够针对特定请求将mode 设置为no-cors

环境
  • Axios 0.20.0
  • TypeScript 4.0.3

【问题讨论】:

    标签: typescript axios cors


    【解决方案1】:

    mode 不支持配置 axios 请求。

    modeRequest 上可用,但在XMLHttpRequest 上不可用。 如果 XMLHttpRequest 可用,则默认被 axios 使用:(defaults.js)

    function getDefaultAdapter() {
      var adapter;
      if (typeof XMLHttpRequest !== 'undefined') {
        // For browsers use XHR adapter
        adapter = require('./adapters/xhr');
      } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
        // For node use HTTP adapter
        adapter = require('./adapters/http');
      }
      return adapter;
    }
    

    见:similar problem in axios repo

    【讨论】:

      【解决方案2】:

      您是否尝试在请求中设置sec-fetch-mode: no-cors 标头?

      const mediaUrl: string = await client
        .get(paths.moment.media.getMediaUrl({ mediaId: media.id }), {
          headers: {
            'sec-fetch-mode': 'no-cors',
          }
        })
      .then(({ data }: { data: string }): string => data);
      

      【讨论】:

      • 是的,我之前尝试过,但没有成功。
      猜你喜欢
      • 2021-12-25
      • 2020-03-05
      • 2021-12-26
      • 2021-11-07
      • 2021-09-10
      • 2020-06-14
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多