4

我对创建 API 包装器并使用 es6 类从 axios 扩展很感兴趣。这怎么可能?axios 有一个方法 .create() 允许你生成一个新的 axios 对象

class Api extends Axios {
  constructor(...args){
    super(..args)
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

我知道我可以访问这个let instance = axios.create()

有什么想法吗?

尝试 1

import axios from 'axios'
const Axios = axios.create()

class Api extends Axios {
  constructor (...args) {
    super(...args)
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

let api = new Api()

api.cancelOrder('hi')
  .then(console.log)
  .catch(console.log)

尝试 2

import axios from 'axios'

class Axios {
  constructor () {
    return axios.create()
  }
}

class Api extends Axios {
  constructor () {
    super()
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}

let api = new Api()

console.log(api.__proto__)

api.cancelOrder('hi')
  .then(console.log)
  .catch(console.log)
4

5 回答 5

2

axios当前不导出Axios它在内部使用的对象。

.create()方法仅实例化一个新实例。

// Factory for creating new instances
axios.create = function create(defaultConfig) {
  return new Axios(defaultConfig);
};

我创建了一个导出Axios类的 pr。

https://github.com/reggi/axios/commit/7548f2f79d20031cd89ea7c2c83f6b3a9c2b1da4

还有一个github问题:

https://github.com/mzabriskie/axios/issues/320

于 2016-05-13T20:25:16.660 回答
2

If you look at the source code of they do not seem to expose the "class" for Axios, only an instance.

I do not believe that an instance object can be extended in es6.


Your second attempt seems most viable, but if you want to emulate every single axios method, you may have a lot of overhead.

于 2016-05-13T19:23:29.643 回答
1

你可以安装这个包:npm i axios-es6-class

于 2020-05-08T02:28:11.190 回答
1
import axios, { Axios } from 'axios';

class Api extends Axios {
  constructor () {
    super()
    this.defaults.baseURL = 'https://api.com'
  }
  cancelOrder (id) {
    return this.put(`/cancel/order/${id}`)
  }
}
于 2020-12-30T23:02:51.600 回答
1

我还想创建一个类,它允许我创建多个具有预定义默认值的实例。这是我的解决方案。

import axios from 'axios'

export class Axios {
    constructor() {
        return axios.create({
            baseURL: 'http://127.0.0.1:8080/',
            headers: {
                Authorization: 'AUTH TOKEN FROM INSTANCE',
                'Content-Type': 'application/json',
            },
        })
   }

}

const db = new Axios()

db.get('/your_url').then().catch()
于 2020-11-12T18:50:21.483 回答