Vuejs- network

What is 1.axios

It is based on the http client browser and promise for node.js end a js library, based on Promise to take this understanding it.

2. Features

Node.js the browser and the 
support promise 
to intercept the request and response 
energy conversion request and response data 
can cancel the request 
automatically convert the data browser JSON 
supports from CSRF

3. Install

1, using the install Axios --save npm install npm 
2, using the install Axios --save bower mounting bower 
. 3, is introduced directly cdn <script src = "https://unpkg.com/axios/dist/axios.min.js "> </ script>

4. Basic use

4.1 GET request

// to send the request through a given ID 
axios.get ( '/ User ID = 12345?') 
 .Then (function (Response) {    
 the console.log (Response);   
})   
.catch (function (ERR) {     
Console. log (ERR);   
}); 
than // request may be transmitted in this way 
axios.get ( '/ User', 
{the params: {   
  ID: 12345   
  } 
}) .then (function (Response) { the console.log (Response); }) .catch (function (ERR) { the console.log (ERR); });

4.2 POST request

axios.post('/user',
{
firstName:'Fred',
lastName:'Flintstone'
}
)
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});

A plurality of concurrent requests disposable 4.3

function 
 getUserAccount () { 
     return axios.get ( '/ User / 12345'); 
} function getUserPermissions () { return axios.get ( '/ User / 12345 / Permissions'); } axios.all ([getUserAccount (), getUserPermissions ()]) .then (axios.spread (function (acct, PERMS) { // when both requests are completed triggers this function, the two parameters representing the result returned }))

5. axios API

Using the corresponding configuration file axios change some default configuration or request, customized

(1) axios(config)

// send a request `POST` 

Axios ({ 
    Method:" the POST ", 
    URL: '/ User / 12345', 
    Data: { 
        firstName:" Fred ", 
        lastName:" Flintstone " 
    } 
});

(2) axios(url[,config])

// `GET` transmitting a request (request for default mode) 
Axios ( '/ User / 12345');

5.2 alias request mode, where all aliases provide a convenient way for all requests have been supported

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 we use the alias method, url, method, data does not require these parameters declared in the configuration request is used in front of the 4.1, 4.2 alias manner.

5.3 concurrent requests (concurrency), that is, to help handle concurrent requests helper functions

// iterable is a possible iterative parameters such as arrays and other 
axios.all (Iterable) 
// callback to wait until all requests are completed before execution 
axios.spread (callback)

5.4 Creating a axios instance, you can customize its configuration

1) axios.create([config])

var instance = axios.create({
  baseURL:"https://some-domain.com/api/",
  timeout:1000,
  headers: {'X-Custom-Header':'foobar'}
});

Method (2) example

Note that you have defined configuration and use examples create the configuration created by the merger of

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]])

7 return requested content

{ 
  Data: {}, 
  // server returns data 
  Status: 200 is, 
  // http returned from the server status text 
  the statusText: 'the OK', 
  // response headers 
  headers: {}, 
  // `request is config` some configuration information when the 
  config: {} 
}

Get the server response information

axios.get ( '/ User / 12345') 
  .then (function (RES) {    
 // RES is a custom parameter, representative of all the contents of the request returns     
the console.log (res.data);   
the console.log (RES. Status);   
the console.log (res.statusText);    
the console.log (res.headers);    
the console.log (res.config); 
})

8 default settings

You can set the default configuration, valid for all requests

8.1 The global default configuration

axios.defaults.baseURL = 'http://api.exmple.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';

8.2 default settings defined from Example

// default configuration when creating an instance 
var = axios.create instance ({    
 the baseURL: 'https://api.example.com' 
});   
// create an instance of time when the configuration changes 
instance.defaults.headers.common [ "Authorization"] = AUTH_TOKEN;

8.3 has priority configuration

config configuration will be combined in a priority order is the default configuration lib / defauts.js, and then the default configuration example, the configuration is the last request in the config parameters, the next higher level, the latter will covering the previous example.

// Create an instance when using the default directory configuration libray 
// Here configured timeout value of 0, the default value from the libray
var instance axios.create = ();
// return overrides the default from the library // now will be issued after all requests have to wait instance.defaults.timeout = 2500 2.5S;
// 2.5S herein before timeout back cover becomes 5S
instance.get ( '/ longRequest', {timeout: 5000 });

9 interceptor

This is the key, often

Add a request interceptor

axios.interceptors.request.use (function (config) {	 
// do nothing request before sending	 
the let pathname = location.pathname;	 
IF (localStorage.getItem ( 'token')) {		 
IF (pathname = '/' &&! ! = pathname '/ Login') {	 
   .headers.common [ 'token'] = localStorage.getItem ( 'token');	 
} 
}	 
return config; 
}, 
function (error) {	 
// do nothing to request error	 
return Promise .reject (error); 
});

Add a response interceptor

axios.interceptors.response.use (function (Response) { 
	return Response;} 
, function (error) { 
	IF (error.response) {		 
Switch (error.response.status) {			 
// return 401, and jumps to clear token information to the login page			 
Case 401:			 
localStorage.removeItem ( 'token');			 
router.replace ({				 
path: '/ Login'				 
// login is successful jump browse the current page				 
// query: {redirect: router.currentRoute.fullPath}			 
})		 
}		 
// returns the error message returned interface		 
return Promise.reject (error.response.data);	 
}});

9.2 Cancellation interceptor 

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

axios Example 9.3 was added to the custom interceptor

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

10. Error Handling

axios.get ( '/ User / 12345') 
 .catch (function (error) {    
 IF (error.response) {      
 // request has been sent, the server returns the response status do not within the scope of 2xx     
 console.log (error. response.data);      
 the console.log (error.response.status);      
 the console.log (error.response.header);   
  } the else {     
  // set of errors that are triggered when the request      
 console.log ( 'error', error .message);    
 }     
the console.log (error.config);   
});

  

 

 

 

  

  

  

 

 

Guess you like

Origin www.cnblogs.com/cainame/p/12096746.html