1.axios特徵html
axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端,它自己具備如下特徵:vue
//使用npm $ npm install axios //使用bower $ bower install axios //或者使用cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
安裝其餘插件的時候,能夠直接在 main.js 中引入並使用 Vue.use()來註冊,可是 axios並非vue插件,因此不能 使用Vue.use(),因此只能在每一個須要發送請求的組件中即時引入。node
爲了解決這個問題,咱們在引入 axios 以後,經過修改原型鏈,來更方便的使用。ios
//main.jsnpm
import axios from 'axios'
Vue.prototype.$http = axios
3.使用 $http命令axios
在 main.js 中添加了這兩行代碼以後,就能直接在組件的 methods 中使用 $http命令api
methods: { postData () { this.$http({ method: 'post', url: '/user', data: { name: 'xiaoming', info: '12' } }) }
2、下面來介紹axios的具體使用:瀏覽器
// 發送一個 POST 請求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// 發送一個 GET 請求 (GET請求是默認請求模式) axios('/user/12345');
爲了方便起見,已經爲全部支持的請求方法提供了別名。當使用別名方法時,不須要在config中指定url,method和data屬性。服務器
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]])
// 向具備指定ID的用戶發出請求 $http.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 也能夠經過 params 對象傳遞參數 $http.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2.2執行 POST 請求併發
$http.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3.併發
幫助函數處理併發請求。
執行多個併發請求
function getUserAccount() { return $http.get('/user/12345'); } function getUserPermissions() { return $http.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then($http.spread(function (acct, perms) { //兩個請求現已完成 }));
4.建立實例
您可使用自定義配置建立axios的新實例。
axios.create([config])
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
可用的實例方法以下所示。 指定的配置將與實例配置合併。
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])
config詳細見:http://www.javashuo.com/article/p-qoudlanx-ho.html
5.響應格式
請求的相應包含如下信息
{ // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} }
使用 then 時,您將收到以下響應:
axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
6.配置默認值
6.1全局默認值
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';
6.2自定義實例的默認值
// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
6.3配置的優先級
config中配置的值>實例方法的defaults的配置值>庫中defaults的配置值
// Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library //庫 const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out //實例的配置值 instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time //config的配置值 instance.get('/longRequest', { timeout: 5000 });
7.攔截器
你能夠截取請求或響應在被 then 或者 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); });
//去除攔截器 const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
8.處理錯誤
axios.get('/ user / 12345') .catch(function(error){ if(error.response){ //請求已發出,但服務器使用狀態代碼進行響應 //落在2xx的範圍以外 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { //在設置觸發錯誤的請求時發生了錯誤 console.log('Error',error.message); }} console.log(error.config); });
您可使用validateStatus配置選項定義自定義HTTP狀態碼錯誤範圍。
axios.get('/ user / 12345',{ validateStatus:function(status){ return status < 500; //僅當狀態代碼大於或等於500時拒絕 }} })
9.取消請求
使用cancel token取消請求
9.1使用CancelToken.source工廠建立一個cancel token
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.');
9.2經過傳遞一個執行函數給CancelToken構造函數來建立一個cancel token:
const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel();