为什么axios返回包装函数?

时间:2020-11-09 09:27:10

标签: javascript axios

axios返回包装函数,但我想在其中使用 axios.CancelToken 。为什么会这样?

import axios from "axios";

const instance = axios.create({
  baseURL: appUrl,
  timeout: 0,
});

instance.interceptors.request.use(
  function(config) {
    console.log(instance);
  }
);

export const $axios = instance;

enter image description here

1 个答案:

答案 0 :(得分:2)

CancelTokenaxios的静态属性。这不是实例属性。

如果您使用的是ES6模块导入,引用它的一种简单方法是导入

import axios, { CancelToken } from "axios"

const instance = axios.create({
  baseURL: appUrl,
  timeout: 0,
});

const source = CancelToken.source()

instance.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel("Operation cancelled by the user.");

这实际上只是

的短版
import axios from "axios"
const CancelToken = axios.CancelToken