axios-observable
Observable (as opposed to Promise) based HTTP client for the browser and node.js
Want to use axios in a rxjs (observable) way? There we go!
This API of axios-observable is almost same as API of axios, giving you smooth transition. So the documentation mirrors the one of axios (A few exceptions will be cleared pointed out).
Features
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Observable API
- Intercept request and response
- Transform request and response data
- (NEW in v1.1.0) Cancel requests through unsubscribe
- Automatic transforms for JSON data
- Client side support for protecting against XSRF
Installing
Using npm:
note: axios
and rxjs
are peer dependencies.
$ npm install axios rxjs axios-observable
Example
Performing a GET
request
import Axios from 'axios-observable';
Axios.get('/user?ID=12345')
.subscribe(
response => console.log(response),
error => console.log(error)
);
Axios.get('/user?ID=12345'), {
params: {
ID: 12345
}
})
.subscribe(
response => console.log(response),
error => console.log(error)
);
Performing a POST
request
Axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.subscribe(
response => console.log(response),
error => console.log(error)
);
Why observable is better than Promise?
You can do much more! rxjs provides tons of operators to let you gracefully control your request.
Example, retry 3 times after failures.
Axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.pipe(
retry(3)
)
.subscribe(
response => console.log(response),
error => console.log(error)
);
axios-observable API
Yeah! We use the exact same config object as axios.
Axios.request(config) (We don't support using Axios as a function as opposed to axios library)
The example below is wrong!
Axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
use Axios.request(config) instead
Axios.request({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Axios.request({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.subscribe(response => {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
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.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
as opposed to axios using all
and spread
, rxjs has a much better way of handling concurrency.
Creating an instance
You can create a new instance of Axios with a custom config.
Axios.create([config])
const instance = Axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
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#post(url[, data[, config]])
Axios#put(url[, data[, config]])
Axios#patch(url[, data[, config]])
Request Config (same as axios, typed with AxiosRequestConfig
if using TypeScript)
These are the available config options for making requests. Only the url
is required. Requests will default to GET
if method
is not specified.
{
url: '/user',
method: 'get',
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data, headers) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: {
firstName: 'Fred'
},
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
responseType: 'json',
responseEncoding: 'utf8',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function (progressEvent) {
},
onDownloadProgress: function (progressEvent) {
},
maxContentLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 5,
socketPath: null,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken(function (cancel) {
})
}
Response Schema (same as axios, typed with AxiosResponse<T>
if using TypeScript)
The response for a request contains the following information.
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
Axios.defaults.baseURL = 'https://api.example.com';
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Custom instance defaults
const instance = Axios.create({
baseURL: 'https://api.example.com'
});
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.
const instance = Axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', {
timeout: 5000
});
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
Axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
Axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
If you may need to remove an interceptor later you can.
const myInterceptor = Axios.interceptors.request.use(function () {});
Axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
const instance = Axios.create();
instance.interceptors.request.use(function () {});
You can define a custom HTTP status code error range using the validateStatus
config option.
Axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500;
}
})
Cancellation (Big win for axios-observable)
As opposed to axios which using cancel token, rxjs comes with a more natural way - unsubscribe
const subscription = Axios.get('/user/12345').subscribe(response => console.log(response));
subscription.unsubscribe();
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:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
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:
const qs = require('qs');
Axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (ES6),
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
Axios.request(options);
Node.js
In node.js, you can use the querystring
module as follows:
const querystring = require('querystring');
Axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
You can also use the qs
library.
TypeScript
axios-observable includes TypeScript definitions.
import Axios from 'axios-observable';
Axios.get('/user?ID=12345');
License
MIT