README.md 7.8 KB
Newer Older
M
mzabriskie 已提交
1 2 3 4 5 6
#axios

[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![npm downloadsi](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![build status](https://img.shields.io/travis/mzabriskie/axios.svg?style=flat-square)](https://travis-ci.org/mzabriskie/axios)
[![dependency status](https://img.shields.io/david/mzabriskie/axios.svg?style=flat-square)](https://david-dm.org/mzabriskie/axios)
M
Matt Zabriskie 已提交
7

M
mzabriskie 已提交
8
Promise based HTTP client for the browser and node.js
M
Matt Zabriskie 已提交
9 10 11

## Features

M
mzabriskie 已提交
12 13
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
- Make [http](http://nodejs.org/api/http.html) requests from node.js
M
mzabriskie 已提交
14
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
M
mzabriskie 已提交
15
- Intercept request and response
M
mzabriskie 已提交
16
- Transform request and response data
M
Matt Zabriskie 已提交
17
- Automatic transforms for JSON data
M
mzabriskie 已提交
18
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
M
Matt Zabriskie 已提交
19

M
Matt Zabriskie 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33
## Installing

Using bower:

```bash
$ bower install axios
```

Using npm:

```bash
$ npm install axios
```

M
mzabriskie 已提交
34
## Compatibility
M
Matt Zabriskie 已提交
35 36 37

Tested to work with >=IE8, Chrome, Firefox, Safari, and Opera.

M
Matt Zabriskie 已提交
38 39 40 41 42 43 44
## Example

Performing a `GET` request

```js
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
M
mzabriskie 已提交
45 46 47 48 49 50
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });
M
Matt Zabriskie 已提交
51 52 53
	
// Optionally the request above could also be done as
axios.get('/user', {
M
mzabriskie 已提交
54 55 56 57 58 59 60 61 62 63
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });
M
Matt Zabriskie 已提交
64 65 66 67 68 69
```

Performing a `POST` request

```js
axios.post('/user', {
M
mzabriskie 已提交
70 71 72 73 74 75 76 77 78
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });
M
Matt Zabriskie 已提交
79 80
```

M
Matt Zabriskie 已提交
81 82
Performing multiple concurrent requests

M
Matt Zabriskie 已提交
83
```js
M
Matt Zabriskie 已提交
84
function getUserAccount() {
M
mzabriskie 已提交
85
  return axios.get('/user/12345');
M
Matt Zabriskie 已提交
86 87 88
}

function getUserPermissions() {
M
mzabriskie 已提交
89
  return axios.get('/user/12345/permissions');
M
Matt Zabriskie 已提交
90 91 92
}

axios.all([getUserAccount(), getUserPermissions()])
M
mzabriskie 已提交
93 94 95
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
M
Matt Zabriskie 已提交
96 97
```

M
mzabriskie 已提交
98
## axios API
M
Matt Zabriskie 已提交
99

M
Matt Zabriskie 已提交
100
Requests can be made by passing the relevant config to `axios`.
M
Matt Zabriskie 已提交
101

M
Matt Zabriskie 已提交
102
##### axios(config)
M
Matt Zabriskie 已提交
103 104 105

```js
axios({
M
mzabriskie 已提交
106 107
  method: 'get',
  url: '/user/12345'
M
Matt Zabriskie 已提交
108 109 110 111 112 113 114
});
```

### Request method aliases

For convenience aliases have been provided for all supported request methods.

M
Matt Zabriskie 已提交
115 116 117 118 119 120
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.post(url[, data[, config]])
##### axios.put(url[, data[, config]])
##### axios.patch(url[, data[, config]])
M
Matt Zabriskie 已提交
121 122

###### NOTE
M
Matt Zabriskie 已提交
123
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
M
Matt Zabriskie 已提交
124

M
Matt Zabriskie 已提交
125 126
### Concurrency

M
Matt Zabriskie 已提交
127 128
Helper functions for dealing with concurrent requests.

M
Matt Zabriskie 已提交
129 130 131
##### axios.all(iterable)
##### axios.spread(callback)

M
mzabriskie 已提交
132
## Request API
M
Matt Zabriskie 已提交
133

M
Matt Zabriskie 已提交
134
This is the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
M
Matt Zabriskie 已提交
135

M
Matt Zabriskie 已提交
136 137
```js
{
M
mzabriskie 已提交
138 139 140 141 142 143 144 145 146 147 148
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an ArrayBuffer
  transformRequest: [function (data) {
    // Do whatever you want to transform the data
M
Matt Zabriskie 已提交
149
	
M
mzabriskie 已提交
150 151 152 153 154 155 156
    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
M
Matt Zabriskie 已提交
157
	
M
mzabriskie 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `param` are the URL parameters to be sent with the request
  params: {
    ID: 12345
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
  data: {
    firstName: 'Fred'
  },

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text'
  responseType: 'json', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN' // default
M
Matt Zabriskie 已提交
189 190 191 192 193
}
```

## Response API

M
mzabriskie 已提交
194 195 196 197
The response for a request contains the following information.

```js
{
M
mzabriskie 已提交
198 199 200 201 202
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,
M
mzabriskie 已提交
203 204 205
  
  // `statusText` is the HTTP status message from the server response
  status: 'OK',
M
mzabriskie 已提交
206 207 208 209 210 211

  // `headers` the headers that the server responded with
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {}
M
mzabriskie 已提交
212 213 214
}
```

M
mzabriskie 已提交
215
When using `then` or `catch`, you will receive the response as follows:
M
Matt Zabriskie 已提交
216

M
Matt Zabriskie 已提交
217
```js
M
Matt Zabriskie 已提交
218
axios.get('/user/12345')
M
mzabriskie 已提交
219 220 221
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
M
mzabriskie 已提交
222
    console.log(response.statusText);
M
mzabriskie 已提交
223 224 225 226 227
    console.log(response.headers);
    console.log(response.config);
});
```

M
mzabriskie 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
## Interceptors

You can intercept requests or responses before they are handled by `then` or `catch`.

```js
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });
```

If you may need to remove an interceptor later you can.

```js
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
```

M
mzabriskie 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
## Handling Errors

```js
axios.get('/user/12345')
  .catch(function (response) {
    if (response instanceof Error) {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', response.message);
    } else {
      // The request was made, but the server responded with a status code
      // that falls out of the range of 2xx
      console.log(response.data);
      console.log(response.status);
      console.log(response.headers);
      console.log(response.config);
    }
  });
M
mzabriskie 已提交
276 277
```

278
## TypeScript Definition
M
mzabriskie 已提交
279
axios includes a [TypeScript](http://typescriptlang.org) definition.
280 281 282 283 284 285
```typescript
/// <reference path="axios.d.ts" />
import axios = require('axios');
axios.get('/user?ID=12345');
```

M
Matt Zabriskie 已提交
286
## Credits
M
Matt Zabriskie 已提交
287

M
Matt Zabriskie 已提交
288 289 290
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.

axios uses the [es6-promise](https://github.com/jakearchibald/es6-promise) polyfill by [Jake Archibald](https://github.com/jakearchibald). Until we [can use](http://caniuse.com/promises) ES6 Promises natively in all browsers, this polyfill is a life saver.
M
Matt Zabriskie 已提交
291 292 293

## License

294
MIT