项目作者: brentonhouse

项目描述 :
Titanium module for using axios with http/https/api calls
高级语言: JavaScript
项目地址: git://github.com/brentonhouse/titanium-axios.git
创建时间: 2019-06-05T21:42:39Z
项目社区:https://github.com/brentonhouse/titanium-axios

开源协议:MIT License

下载




🪦 RIP Axway Amplify Titanium (2010 - 2022)





RIP Axway Amplify Titanium (2010 - 2022)





🪦 RIP Axway Amplify Titanium (2010 - 2022)





🛑 This project is no longer being maintained 🛑







@titanium/axios

@titanium/axios

Titanium axios is a fork of axios that adds support for Titanium native mobile apps.

This version of @titanium/axios is based on axios 0.18.0

Many thanks to @janvennemann for creating the Titanium adapter!

Promise based HTTP client for Titanium Mobile Native Apps

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Installing

Using npm:

  1. $ npm install @titanium/axios

Using yarn:

  1. $ yarn add @titanium/axios

Example

note: CommonJS usage

In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require() use the following approach:

  1. const axios = require('axios').default;
  2. // axios.<method> will now provide autocomplete and parameter typings

Performing a GET request

  1. const axios = require('axios');
  2. // Make a request for a user with a given ID
  3. axios.get('/user?ID=12345')
  4. .then(function (response) {
  5. // handle success
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. // handle error
  10. console.log(error);
  11. })
  12. .finally(function () {
  13. // always executed
  14. });
  15. // Optionally the request above could also be done as
  16. axios.get('/user', {
  17. params: {
  18. ID: 12345
  19. }
  20. })
  21. .then(function (response) {
  22. console.log(response);
  23. })
  24. .catch(function (error) {
  25. console.log(error);
  26. })
  27. .finally(function () {
  28. // always executed
  29. });
  30. // Want to use async/await? Add the `async` keyword to your outer function/method.
  31. async function getUser() {
  32. try {
  33. const response = await axios.get('/user?ID=12345');
  34. console.log(response);
  35. } catch (error) {
  36. console.error(error);
  37. }
  38. }

NOTE: async/await is part of ECMAScript 2017 and is not supported in Internet
Explorer and older browsers, so use with caution.

Performing a POST request

  1. axios.post('/user', {
  2. firstName: 'Fred',
  3. lastName: 'Flintstone'
  4. })
  5. .then(function (response) {
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. console.log(error);
  10. });

Performing multiple concurrent requests

  1. function getUserAccount() {
  2. return axios.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then(axios.spread(function (acct, perms) {
  9. // Both requests are now complete
  10. }));

axios API

Requests can be made by passing the relevant config to axios.

axios(config)
  1. // Send a POST request
  2. axios({
  3. method: 'post',
  4. url: '/user/12345',
  5. data: {
  6. firstName: 'Fred',
  7. lastName: 'Flintstone'
  8. }
  9. });
  1. // GET request for remote image
  2. axios({
  3. method: 'get',
  4. url: 'http://bit.ly/2mTM3nY',
  5. responseType: 'stream'
  6. })
  7. .then(function (response) {
  8. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  9. });
axios(url[, config])
  1. // Send a GET request (default method)
  2. axios('/user/12345');

Request method aliases

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

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE

When using the alias methods url, method, and data properties don’t need to be specified in config.

Concurrency

Helper functions for dealing with concurrent requests.

axios.all(iterable)
axios.spread(callback)

Creating an instance

You can create a new instance of axios with a custom config.

axios.create([config])
  1. const instance = axios.create({
  2. baseURL: 'https://some-domain.com/api/',
  3. timeout: 1000,
  4. headers: {'X-Custom-Header': 'foobar'}
  5. });

Instance methods

The available instance methods are listed below. The specified config will be merged with the instance config.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

Request Config

These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.

  1. {
  2. // `url` is the server URL that will be used for the request
  3. url: '/user',
  4. // `method` is the request method to be used when making the request
  5. method: 'get', // default
  6. // `baseURL` will be prepended to `url` unless `url` is absolute.
  7. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  8. // to methods of that instance.
  9. baseURL: 'https://some-domain.com/api/',
  10. // `transformRequest` allows changes to the request data before it is sent to the server
  11. // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  12. // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  13. // FormData or Stream
  14. // You may modify the headers object.
  15. transformRequest: [function (data, headers) {
  16. // Do whatever you want to transform the data
  17. return data;
  18. }],
  19. // `transformResponse` allows changes to the response data to be made before
  20. // it is passed to then/catch
  21. transformResponse: [function (data) {
  22. // Do whatever you want to transform the data
  23. return data;
  24. }],
  25. // `headers` are custom headers to be sent
  26. headers: {'X-Requested-With': 'XMLHttpRequest'},
  27. // `params` are the URL parameters to be sent with the request
  28. // Must be a plain object or a URLSearchParams object
  29. params: {
  30. ID: 12345
  31. },
  32. // `paramsSerializer` is an optional function in charge of serializing `params`
  33. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  34. paramsSerializer: function (params) {
  35. return Qs.stringify(params, {arrayFormat: 'brackets'})
  36. },
  37. // `data` is the data to be sent as the request body
  38. // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  39. // When no `transformRequest` is set, must be of one of the following types:
  40. // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  41. // - Browser only: FormData, File, Blob
  42. // - Node only: Stream, Buffer
  43. data: {
  44. firstName: 'Fred'
  45. },
  46. // syntax alternative to send data into the body
  47. // method post
  48. // only the value is sent, not the key
  49. data: 'Country=Brasil&City=Belo Horizonte',
  50. // `timeout` specifies the number of milliseconds before the request times out.
  51. // If the request takes longer than `timeout`, the request will be aborted.
  52. timeout: 1000, // default is `0` (no timeout)
  53. // `withCredentials` indicates whether or not cross-site Access-Control requests
  54. // should be made using credentials
  55. withCredentials: false, // default
  56. // `adapter` allows custom handling of requests which makes testing easier.
  57. // Return a promise and supply a valid response (see lib/adapters/README.md).
  58. adapter: function (config) {
  59. /* ... */
  60. },
  61. // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  62. // This will set an `Authorization` header, overwriting any existing
  63. // `Authorization` custom headers you have set using `headers`.
  64. // Please note that only HTTP Basic auth is configurable through this parameter.
  65. // For Bearer tokens and such, use `Authorization` custom headers instead.
  66. auth: {
  67. username: 'janedoe',
  68. password: 's00pers3cret'
  69. },
  70. // `responseType` indicates the type of data that the server will respond with
  71. // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  72. // browser only: 'blob'
  73. responseType: 'json', // default
  74. // `responseEncoding` indicates encoding to use for decoding responses
  75. // Note: Ignored for `responseType` of 'stream' or client-side requests
  76. responseEncoding: 'utf8', // default
  77. // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  78. xsrfCookieName: 'XSRF-TOKEN', // default
  79. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  80. xsrfHeaderName: 'X-XSRF-TOKEN', // default
  81. // `onUploadProgress` allows handling of progress events for uploads
  82. onUploadProgress: function (progressEvent) {
  83. // Do whatever you want with the native progress event
  84. },
  85. // `onDownloadProgress` allows handling of progress events for downloads
  86. onDownloadProgress: function (progressEvent) {
  87. // Do whatever you want with the native progress event
  88. },
  89. // `maxContentLength` defines the max size of the http response content in bytes allowed
  90. maxContentLength: 2000,
  91. // `validateStatus` defines whether to resolve or reject the promise for a given
  92. // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  93. // or `undefined`), the promise will be resolved; otherwise, the promise will be
  94. // rejected.
  95. validateStatus: function (status) {
  96. return status >= 200 && status < 300; // default
  97. },
  98. // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  99. // If set to 0, no redirects will be followed.
  100. maxRedirects: 5, // default
  101. // `socketPath` defines a UNIX Socket to be used in node.js.
  102. // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  103. // Only either `socketPath` or `proxy` can be specified.
  104. // If both are specified, `socketPath` is used.
  105. socketPath: null, // default
  106. // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  107. // and https requests, respectively, in node.js. This allows options to be added like
  108. // `keepAlive` that are not enabled by default.
  109. httpAgent: new http.Agent({ keepAlive: true }),
  110. httpsAgent: new https.Agent({ keepAlive: true }),
  111. // 'proxy' defines the hostname and port of the proxy server.
  112. // You can also define your proxy using the conventional `http_proxy` and
  113. // `https_proxy` environment variables. If you are using environment variables
  114. // for your proxy configuration, you can also define a `no_proxy` environment
  115. // variable as a comma-separated list of domains that should not be proxied.
  116. // Use `false` to disable proxies, ignoring environment variables.
  117. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  118. // supplies credentials.
  119. // This will set an `Proxy-Authorization` header, overwriting any existing
  120. // `Proxy-Authorization` custom headers you have set using `headers`.
  121. proxy: {
  122. host: '127.0.0.1',
  123. port: 9000,
  124. auth: {
  125. username: 'mikeymike',
  126. password: 'rapunz3l'
  127. }
  128. },
  129. // `cancelToken` specifies a cancel token that can be used to cancel the request
  130. // (see Cancellation section below for details)
  131. cancelToken: new CancelToken(function (cancel) {
  132. })
  133. }

Response Schema

The response for a request contains the following information.

  1. {
  2. // `data` is the response that was provided by the server
  3. data: {},
  4. // `status` is the HTTP status code from the server response
  5. status: 200,
  6. // `statusText` is the HTTP status message from the server response
  7. statusText: 'OK',
  8. // `headers` the headers that the server responded with
  9. // All header names are lower cased
  10. headers: {},
  11. // `config` is the config that was provided to `axios` for the request
  12. config: {},
  13. // `request` is the request that generated this response
  14. // It is the last ClientRequest instance in node.js (in redirects)
  15. // and an XMLHttpRequest instance in the browser
  16. request: {}
  17. }

When using then, you will receive the response as follows:

  1. axios.get('/user/12345')
  2. .then(function (response) {
  3. console.log(response.data);
  4. console.log(response.status);
  5. console.log(response.statusText);
  6. console.log(response.headers);
  7. console.log(response.config);
  8. });

When using catch, or passing a rejection callback as second parameter of then, the response will be available through the error object as explained in the Handling Errors section.

Config Defaults

You can specify config defaults that will be applied to every request.

Global axios defaults

  1. axios.defaults.baseURL = 'https://api.example.com';
  2. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  3. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Custom instance defaults

  1. // Set config defaults when creating the instance
  2. const instance = axios.create({
  3. baseURL: 'https://api.example.com'
  4. });
  5. // Alter defaults after instance has been created
  6. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Config order of precedence

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here’s an example.

  1. // Create an instance using the config defaults provided by the library
  2. // At this point the timeout config value is `0` as is the default for the library
  3. const instance = axios.create();
  4. // Override timeout default for the library
  5. // Now all requests using this instance will wait 2.5 seconds before timing out
  6. instance.defaults.timeout = 2500;
  7. // Override timeout for this request as it's known to take a long time
  8. instance.get('/longRequest', {
  9. timeout: 5000
  10. });

Interceptors

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

  1. // Add a request interceptor
  2. axios.interceptors.request.use(function (config) {
  3. // Do something before request is sent
  4. return config;
  5. }, function (error) {
  6. // Do something with request error
  7. return Promise.reject(error);
  8. });
  9. // Add a response interceptor
  10. axios.interceptors.response.use(function (response) {
  11. // Any status code that lie within the range of 2xx cause this function to trigger
  12. // Do something with response data
  13. return response;
  14. }, function (error) {
  15. // Any status codes that falls outside the range of 2xx cause this function to trigger
  16. // Do something with response error
  17. return Promise.reject(error);
  18. });

If you need to remove an interceptor later you can.

  1. const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  2. axios.interceptors.request.eject(myInterceptor);

You can add interceptors to a custom instance of axios.

  1. const instance = axios.create();
  2. instance.interceptors.request.use(function () {/*...*/});

Handling Errors

  1. axios.get('/user/12345')
  2. .catch(function (error) {
  3. if (error.response) {
  4. // The request was made and the server responded with a status code
  5. // that falls out of the range of 2xx
  6. console.log(error.response.data);
  7. console.log(error.response.status);
  8. console.log(error.response.headers);
  9. } else if (error.request) {
  10. // The request was made but no response was received
  11. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  12. // http.ClientRequest in node.js
  13. console.log(error.request);
  14. } else {
  15. // Something happened in setting up the request that triggered an Error
  16. console.log('Error', error.message);
  17. }
  18. console.log(error.config);
  19. });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

  1. axios.get('/user/12345', {
  2. validateStatus: function (status) {
  3. return status < 500; // Reject only if the status code is greater than or equal to 500
  4. }
  5. })

Using toJSON you get an object with more information about the HTTP error.

  1. axios.get('/user/12345')
  2. .catch(function (error) {
  3. console.log(error.toJSON());
  4. });

Cancellation

You can cancel a request using a cancel token.

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory as shown below:

  1. const CancelToken = axios.CancelToken;
  2. const source = CancelToken.source();
  3. axios.get('/user/12345', {
  4. cancelToken: source.token
  5. }).catch(function (thrown) {
  6. if (axios.isCancel(thrown)) {
  7. console.log('Request canceled', thrown.message);
  8. } else {
  9. // handle error
  10. }
  11. });
  12. axios.post('/user/12345', {
  13. name: 'new name'
  14. }, {
  15. cancelToken: source.token
  16. })
  17. // cancel the request (the message parameter is optional)
  18. source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to the CancelToken constructor:

  1. const CancelToken = axios.CancelToken;
  2. let cancel;
  3. axios.get('/user/12345', {
  4. cancelToken: new CancelToken(function executor(c) {
  5. // An executor function receives a cancel function as a parameter
  6. cancel = c;
  7. })
  8. });
  9. // cancel the request
  10. cancel();

Note: you can cancel several requests with the same cancel token.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

  1. const params = new URLSearchParams();
  2. params.append('param1', 'value1');
  3. params.append('param2', 'value2');
  4. axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

  1. const qs = require('qs');
  2. axios.post('/foo', qs.stringify({ 'bar': 123 }));

Or in another way (ES6),

  1. import qs from 'qs';
  2. const data = { 'bar': 123 };
  3. const options = {
  4. method: 'POST',
  5. headers: { 'content-type': 'application/x-www-form-urlencoded' },
  6. data: qs.stringify(data),
  7. url,
  8. };
  9. axios(options);

Node.js

In node.js, you can use the querystring module as follows:

  1. const querystring = require('querystring');
  2. axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

You can also use the qs library.

NOTE

The qs library is preferable if you need to stringify nested objects, as the querystring method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

Semver

Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.

Promises

axios depends on a native ES6 Promise implementation to be supported.
If your environment doesn’t support ES6 Promises, you can polyfill.

TypeScript

axios includes TypeScript definitions.

  1. import axios from 'axios';
  2. axios.get('/user?ID=12345');

Resources

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT