Installations
npm install haxios
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
16.11.1
NPM Version
8.1.1
Score
69.8
Supply Chain
97.9
Quality
75.5
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (60.07%)
TypeScript (39.37%)
HTML (0.56%)
Developer
Download Statistics
Total Downloads
56,457
Last Day
21
Last Week
95
Last Month
556
Last Year
10,575
GitHub Statistics
16 Stars
58 Commits
2 Watching
1 Branches
15 Contributors
Bundle Size
32.31 kB
Minified
10.58 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.1.2
Package Id
haxios@1.1.2
Unpacked Size
66.81 kB
Size
17.26 kB
File Count
12
NPM Version
8.1.1
Node Version
16.11.1
Total Downloads
Cumulative downloads
Total Downloads
56,457
Last day
-65.6%
21
Compared to previous day
Last week
-43.8%
95
Compared to previous week
Last month
-55.9%
556
Compared to previous month
Last year
-62.2%
10,575
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
haxios - an axios wrapper based on gaxios
provides an axios interface, using gaxios behind the scene
adds following feature to gaxios:
- interceptors
- get,post,..etc methods
- dynamic baseURL ..
- onUploadProgress on client via XHR
- and more to come
not implemented yet:
- cancel request token support tests / matrix .. could work, but unsure.
- fully support and port test library from axios
target support is es6 / modern browsers
Promise based HTTP client for the browser and node.js (supports http2 and more)
Features
- Make fetch from the browser
- Make node-fetch requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests (NOT IMPLENENTED YET / WIP)
- Automatic transforms for JSON data
Browser Support
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 nope |
following text is copied from https://github.com/axios/axios, only adapated to use "haxios" instead. (c) by axios team
Installing
Using npm:
1$ npm install haxios
Using bower:
1$ bower install haxios
Using yarn:
1$ yarn add haxios
Example
note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require()
use the following approach:
1const axios = require('haxios').default; 2 3// axios.<method> will now provide autocomplete and parameter typings
Performing a GET
request
1const axios = require('haxios'); 2 3// Make a request for a user with a given ID 4axios.get('/user?ID=12345') 5 .then(function (response) { 6 // handle success 7 console.log(response); 8 }) 9 .catch(function (error) { 10 // handle error 11 console.log(error); 12 }) 13 .finally(function () { 14 // always executed 15 }); 16 17// Optionally the request above could also be done as 18axios.get('/user', { 19 params: { 20 ID: 12345 21 } 22 }) 23 .then(function (response) { 24 console.log(response); 25 }) 26 .catch(function (error) { 27 console.log(error); 28 }) 29 .finally(function () { 30 // always executed 31 }); 32 33// Want to use async/await? Add the `async` keyword to your outer function/method. 34async function getUser() { 35 try { 36 const response = await axios.get('/user?ID=12345'); 37 console.log(response); 38 } catch (error) { 39 console.error(error); 40 } 41}
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
1axios.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
1function getUserAccount() { 2 return axios.get('/user/12345'); 3} 4 5function getUserPermissions() { 6 return axios.get('/user/12345/permissions'); 7} 8 9axios.all([getUserAccount(), getUserPermissions()]) 10 .then(axios.spread(function (acct, perms) { 11 // Both requests are now complete 12 }));
axios API
Requests can be made by passing the relevant config to axios
.
axios(config)
1// Send a POST request 2axios({ 3 method: 'post', 4 url: '/user/12345', 5 data: { 6 firstName: 'Fred', 7 lastName: 'Flintstone' 8 } 9});
1// GET request for remote image 2axios({ 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) 2axios('/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])
1const 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 5 // `method` is the request method to be used when making the request 6 method: 'get', // default 7 8 // `baseURL` will be prepended to `url` unless `url` is absolute. 9 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs 10 // to methods of that instance. 11 baseURL: 'https://some-domain.com/api/', 12 13 // `transformRequest` allows changes to the request data before it is sent to the server 14 // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' 15 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, 16 // FormData or Stream 17 // You may modify the headers object. 18 transformRequest: [function (data, headers) { 19 // Do whatever you want to transform the data 20 21 return data; 22 }], 23 24 // `transformResponse` allows changes to the response data to be made before 25 // it is passed to then/catch 26 transformResponse: [function (data) { 27 // Do whatever you want to transform the data 28 29 return data; 30 }], 31 32 // `headers` are custom headers to be sent 33 headers: {'X-Requested-With': 'XMLHttpRequest'}, 34 35 // `params` are the URL parameters to be sent with the request 36 // Must be a plain object or a URLSearchParams object 37 params: { 38 ID: 12345 39 }, 40 41 // `paramsSerializer` is an optional function in charge of serializing `params` 42 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) 43 paramsSerializer: function (params) { 44 return Qs.stringify(params, {arrayFormat: 'brackets'}) 45 }, 46 47 // `data` is the data to be sent as the request body 48 // Only applicable for request methods 'PUT', 'POST', and 'PATCH' 49 // When no `transformRequest` is set, must be of one of the following types: 50 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 51 // - Browser only: FormData, File, Blob 52 // - Node only: Stream, Buffer 53 data: { 54 firstName: 'Fred' 55 }, 56 57 // syntax alternative to send data into the body 58 // method post 59 // only the value is sent, not the key 60 data: 'Country=Brasil&City=Belo Horizonte', 61 62 // `timeout` specifies the number of milliseconds before the request times out. 63 // If the request takes longer than `timeout`, the request will be aborted. 64 timeout: 1000, // default is `0` (no timeout) 65 66 // `withCredentials` indicates whether or not cross-site Access-Control requests 67 // should be made using credentials 68 withCredentials: false, // default 69 70 // `adapter` allows custom handling of requests which makes testing easier. 71 // Return a promise and supply a valid response (see lib/adapters/README.md). 72 adapter: function (config) { 73 /* ... */ 74 }, 75 76 // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. 77 // This will set an `Authorization` header, overwriting any existing 78 // `Authorization` custom headers you have set using `headers`. 79 // Please note that only HTTP Basic auth is configurable through this parameter. 80 // For Bearer tokens and such, use `Authorization` custom headers instead. 81 auth: { 82 username: 'janedoe', 83 password: 's00pers3cret' 84 }, 85 86 // `responseType` indicates the type of data that the server will respond with 87 // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' 88 // browser only: 'blob' 89 responseType: 'json', // default 90 91 // `responseEncoding` indicates encoding to use for decoding responses 92 // Note: Ignored for `responseType` of 'stream' or client-side requests 93 responseEncoding: 'utf8', // default 94 95 // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token 96 xsrfCookieName: 'XSRF-TOKEN', // default 97 98 // `xsrfHeaderName` is the name of the http header that carries the xsrf token value 99 xsrfHeaderName: 'X-XSRF-TOKEN', // default 100 101 // `onUploadProgress` allows handling of progress events for uploads 102 onUploadProgress: function (progressEvent) { 103 // Do whatever you want with the native progress event 104 }, 105 106 // `onDownloadProgress` allows handling of progress events for downloads 107 onDownloadProgress: function (progressEvent) { 108 // Do whatever you want with the native progress event 109 }, 110 111 // `maxContentLength` defines the max size of the http response content in bytes allowed 112 maxContentLength: 2000, 113 114 // `validateStatus` defines whether to resolve or reject the promise for a given 115 // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` 116 // or `undefined`), the promise will be resolved; otherwise, the promise will be 117 // rejected. 118 validateStatus: function (status) { 119 return status >= 200 && status < 300; // default 120 }, 121 122 // `maxRedirects` defines the maximum number of redirects to follow in node.js. 123 // If set to 0, no redirects will be followed. 124 maxRedirects: 5, // default 125 126 // `socketPath` defines a UNIX Socket to be used in node.js. 127 // e.g. '/var/run/docker.sock' to send requests to the docker daemon. 128 // Only either `socketPath` or `proxy` can be specified. 129 // If both are specified, `socketPath` is used. 130 socketPath: null, // default 131 132 // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http 133 // and https requests, respectively, in node.js. This allows options to be added like 134 // `keepAlive` that are not enabled by default. 135 httpAgent: new http.Agent({ keepAlive: true }), 136 httpsAgent: new https.Agent({ keepAlive: true }), 137 138 // 'proxy' defines the hostname and port of the proxy server. 139 // You can also define your proxy using the conventional `http_proxy` and 140 // `https_proxy` environment variables. If you are using environment variables 141 // for your proxy configuration, you can also define a `no_proxy` environment 142 // variable as a comma-separated list of domains that should not be proxied. 143 // Use `false` to disable proxies, ignoring environment variables. 144 // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and 145 // supplies credentials. 146 // This will set an `Proxy-Authorization` header, overwriting any existing 147 // `Proxy-Authorization` custom headers you have set using `headers`. 148 proxy: { 149 host: '127.0.0.1', 150 port: 9000, 151 auth: { 152 username: 'mikeymike', 153 password: 'rapunz3l' 154 } 155 }, 156 157 // `cancelToken` specifies a cancel token that can be used to cancel the request 158 // (see Cancellation section below for details) 159 cancelToken: new CancelToken(function (cancel) { 160 }) 161}
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 5 // `status` is the HTTP status code from the server response 6 status: 200, 7 8 // `statusText` is the HTTP status message from the server response 9 statusText: 'OK', 10 11 // `headers` the headers that the server responded with 12 // All header names are lower cased 13 headers: {}, 14 15 // `config` is the config that was provided to `axios` for the request 16 config: {}, 17 18 // `request` is the request that generated this response 19 // It is the last ClientRequest instance in node.js (in redirects) 20 // and an XMLHttpRequest instance in the browser 21 request: {} 22}
When using then
, you will receive the response as follows:
1axios.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
1axios.defaults.baseURL = 'https://api.example.com'; 2axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 3axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Custom instance defaults
1// Set config defaults when creating the instance 2const instance = axios.create({ 3 baseURL: 'https://api.example.com' 4}); 5 6// Alter defaults after instance has been created 7instance.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 3const instance = axios.create(); 4 5// Override timeout default for the library 6// Now all requests using this instance will wait 2.5 seconds before timing out 7instance.defaults.timeout = 2500; 8 9// Override timeout for this request as it's known to take a long time 10instance.get('/longRequest', { 11 timeout: 5000 12});
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
1// Add a request interceptor 2axios.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 10// Add a response interceptor 11axios.interceptors.response.use(function (response) { 12 // Any status code that lie within the range of 2xx cause this function to trigger 13 // Do something with response data 14 return response; 15 }, function (error) { 16 // Any status codes that falls outside the range of 2xx cause this function to trigger 17 // Do something with response error 18 return Promise.reject(error); 19 });
If you need to remove an interceptor later you can.
1const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 2axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
1const instance = axios.create(); 2instance.interceptors.request.use(function () {/*...*/});
Handling Errors
1axios.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.
1axios.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})
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:
1const CancelToken = axios.CancelToken; 2const source = CancelToken.source(); 3 4axios.get('/user/12345', { 5 cancelToken: source.token 6}).catch(function (thrown) { 7 if (axios.isCancel(thrown)) { 8 console.log('Request canceled', thrown.message); 9 } else { 10 // handle error 11 } 12}); 13 14axios.post('/user/12345', { 15 name: 'new name' 16}, { 17 cancelToken: source.token 18}) 19 20// cancel the request (the message parameter is optional) 21source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
1const CancelToken = axios.CancelToken; 2let cancel; 3 4axios.get('/user/12345', { 5 cancelToken: new CancelToken(function executor(c) { 6 // An executor function receives a cancel function as a parameter 7 cancel = c; 8 }) 9}); 10 11// cancel the request 12cancel();
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:
1const params = new URLSearchParams(); 2params.append('param1', 'value1'); 3params.append('param2', 'value2'); 4axios.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:
1const qs = require('qs'); 2axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (ES6),
1import qs from 'qs'; 2const data = { 'bar': 123 }; 3const options = { 4 method: 'POST', 5 headers: { 'content-type': 'application/x-www-form-urlencoded' }, 6 data: qs.stringify(data), 7 url, 8}; 9axios(options);
Node.js
In node.js, you can use the querystring
module as follows:
1const querystring = require('querystring'); 2axios.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.
1import axios from 'axios'; 2axios.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
No vulnerabilities found.
No security vulnerabilities found.