React~Axios - rohit120582sharma/Documentation GitHub Wiki

Introduction

Axios is promise-based and thus we can take advantage of async and await for more readable asynchronous code. We can also intercept and cancel requests, and there’s built-in client side protection against cross site request forgery.

References



Getting started

Install

npm install --save axios

API

axios(config)

// GET request for remote image
axios({
	method:'get',
	url:'http://bit.ly/2mTM3nY',
	responseType:'stream'
})
.then(function(response) {
	response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios.request(config)

axios.get(url[, config])

axios.post(url[, data[, config]])

axios.delete(url[, config])



Base Instance

Axios allows us to create a new instance in which we can define a URL and any other configuration elements.

import axios from 'axios';

// Set config defaults when creating the instance
var instance = axios.create({
	baseURL: 'http://jsonplaceholder.typicode.com/',
	headers: {'X-Custom-Header': 'foobar'}
});


Configuration

Global 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

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

Request Config

{
	// `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

	// `baseURL` will be prepended to `url` unless `url` is absolute
	baseURL: 'https://some-domain.com/api/',

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

	// `params` are the URL parameters to be sent with the request
	// Must be a plain object or a URLSearchParams object
	params: {
		ID: 12345
	},

	// `data` is the data to be sent as the request body
	// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
	data: {
		firstName: 'Fred'
	},

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


Interceptors

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

// Add a request interceptor
var requestInterceptor = 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
var responseInterceptor = 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.

axios.interceptors.request.eject(responseInterceptor);

You can add interceptors to a custom instance of axios.

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


Using async and await

We can make working with promises even simpler with async and await. The await keyword resolves the promise and returns the value which we can assign to a variable.

handleSubmit = async event => {
	event.preventDefault();

	// Promise is resolved and value is inside of the response const.
	const response = await API.delete(`users/${this.state.id}`);

	console.log(response);
	console.log(response.data);
};
⚠️ **GitHub.com Fallback** ⚠️