axios.ts 6.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
import axios, {
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  AxiosInstance,
  AxiosAdapter,
  Cancel,
  CancelToken,
  CancelTokenSource,
  Canceler
} from '../../';

13 14
const config: AxiosRequestConfig = {
  url: '/user',
15
  method: 'get',
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  baseURL: 'https://api.example.com/',
  transformRequest: (data: any) => '{"foo":"bar"}',
  transformResponse: [
    (data: any) => ({ baz: 'qux' })
  ],
  headers: { 'X-FOO': 'bar' },
  params: { id: 12345 },
  paramsSerializer: (params: any) => 'id=12345',
  data: { foo: 'bar' },
  timeout: 10000,
  withCredentials: true,
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
  responseType: 'json',
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
34 35
  onUploadProgress: (progressEvent: any) => {},
  onDownloadProgress: (progressEvent: any) => {},
36 37
  maxContentLength: 2000,
  validateStatus: (status: number) => status >= 200 && status < 300,
38 39 40 41
  maxRedirects: 5,
  proxy: {
    host: '127.0.0.1',
    port: 9000
42 43
  },
  cancelToken: new axios.CancelToken((cancel: Canceler) => {})
44
};
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
const handleResponse = (response: AxiosResponse) => {
  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
  console.log(response.config);
};

const handleError = (error: AxiosError) => {
  if (error.response) {
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else {
    console.log(error.message);
61
  }
62
};
63

64 65 66
axios(config)
  .then(handleResponse)
  .catch(handleError);
N
Nick Uraltsev 已提交
67

68 69 70
axios.get('/user?id=12345')
  .then(handleResponse)
  .catch(handleError);
N
Nick Uraltsev 已提交
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
axios.get('/user', { params: { id: 12345 } })
  .then(handleResponse)
  .catch(handleError);

axios.head('/user')
  .then(handleResponse)
  .catch(handleError);

axios.delete('/user')
  .then(handleResponse)
  .catch(handleError);

axios.post('/user', { foo: 'bar' })
  .then(handleResponse)
  .catch(handleError);

axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
  .then(handleResponse)
  .catch(handleError);

axios.put('/user', { foo: 'bar' })
  .then(handleResponse)
  .catch(handleError);

axios.patch('/user', { foo: 'bar' })
  .then(handleResponse)
  .catch(handleError);

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
// Typed methods
interface User {
  id: number;
  name: string;
}

const handleUserResponse = (response: AxiosResponse<User>) => {
	console.log(response.data.id);
	console.log(response.data.name);
	console.log(response.status);
	console.log(response.statusText);
	console.log(response.headers);
	console.log(response.config);
};

axios.get<User>('/user?id=12345')
	.then(handleUserResponse)
	.catch(handleError);

axios.get<User>('/user', { params: { id: 12345 } })
	.then(handleUserResponse)
	.catch(handleError);

axios.post<User>('/user', { foo: 'bar' })
	.then(handleUserResponse)
	.catch(handleError);

axios.post<User>('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
	.then(handleUserResponse)
	.catch(handleError);

axios.put<User>('/user', { foo: 'bar' })
	.then(handleUserResponse)
	.catch(handleError);

axios.patch<User>('/user', { foo: 'bar' })
	.then(handleUserResponse)
	.catch(handleError);

139 140 141 142 143
// Instances

const instance1: AxiosInstance = axios.create();
const instance2: AxiosInstance = axios.create(config);

144 145 146 147
instance1(config)
  .then(handleResponse)
  .catch(handleError);

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
instance1.request(config)
  .then(handleResponse)
  .catch(handleError);

instance1.get('/user?id=12345')
  .then(handleResponse)
  .catch(handleError);

instance1.get('/user', { params: { id: 12345 } })
  .then(handleResponse)
  .catch(handleError);

instance1.post('/user', { foo: 'bar' })
  .then(handleResponse)
  .catch(handleError);

instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
  .then(handleResponse)
  .catch(handleError);

// Defaults

axios.defaults.baseURL = 'https://api.example.com/';
axios.defaults.headers.common['Authorization'] = 'token';
axios.defaults.headers.post['X-FOO'] = 'bar';
axios.defaults.timeout = 2500;

instance1.defaults.baseURL = 'https://api.example.com/';
instance1.defaults.headers.common['Authorization'] = 'token';
instance1.defaults.headers.post['X-FOO'] = 'bar';
instance1.defaults.timeout = 2500;
179

180 181
// Interceptors

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
const requestInterceptorId: number = axios.interceptors.request.use(
  (config: AxiosRequestConfig) => config,
  (error: any) => Promise.reject(error)
);

axios.interceptors.request.eject(requestInterceptorId);

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => Promise.resolve(config),
  (error: any) => Promise.reject(error)
);

axios.interceptors.request.use((config: AxiosRequestConfig) => config);
axios.interceptors.request.use((config: AxiosRequestConfig) => Promise.resolve(config));

const responseInterceptorId: number = axios.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: any) => Promise.reject(error)
);

axios.interceptors.response.eject(responseInterceptorId);

axios.interceptors.response.use(
  (response: AxiosResponse) => Promise.resolve(response),
  (error: any) => Promise.reject(error)
);

axios.interceptors.response.use((response: AxiosResponse) => response);
axios.interceptors.response.use((response: AxiosResponse) => Promise.resolve(response));
211 212 213 214 215

// Adapters

const adapter: AxiosAdapter = (config: AxiosRequestConfig) => {
  const response: AxiosResponse = {
216
    data: { foo: 'bar' },
217 218 219
    status: 200,
    statusText: 'OK',
    headers: { 'X-FOO': 'bar' },
220
    config
221 222 223 224 225
  };
  return Promise.resolve(response);
};

axios.defaults.adapter = adapter;
226 227 228 229 230 231 232 233 234 235 236 237 238 239

// axios.all

const promises = [
  Promise.resolve(1),
  Promise.resolve(2)
];

const promise: Promise<number[]> = axios.all(promises);

// axios.spread

const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`;
const fn2: (arr: number[]) => string = axios.spread(fn1);
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

// Promises

axios.get('/user')
  .then((response: AxiosResponse) => 'foo')
  .then((value: string) => {});

axios.get('/user')
  .then((response: AxiosResponse) => Promise.resolve('foo'))
  .then((value: string) => {});

axios.get('/user')
  .then((response: AxiosResponse) => 'foo', (error: any) => 'bar')
  .then((value: string) => {});

axios.get('/user')
  .then((response: AxiosResponse) => 'foo', (error: any) => 123)
  .then((value: string | number) => {});

axios.get('/user')
  .catch((error: any) => 'foo')
  .then((value: string) => {});

axios.get('/user')
  .catch((error: any) => Promise.resolve('foo'))
  .then((value: string) => {});
266 267 268 269 270 271 272 273

// Cancellation

const source: CancelTokenSource = axios.CancelToken.source();

axios.get('/user', {
  cancelToken: source.token
}).catch((thrown: AxiosError | Cancel) => {
N
Nick Uraltsev 已提交
274
  if (axios.isCancel(thrown)) {
275 276 277 278 279 280
    const cancel: Cancel = thrown;
    console.log(cancel.message);
  }
});

source.cancel('Operation has been canceled.');