1.axios是基於promise的用於瀏覽器和node.js的HTTP客戶端vue
2.從瀏覽器中建立XMLHttpRequestnode
3.從node.js發出http請求jquery
4.攔截(攔截器) 請求和響應ios
5.轉換請求和響應數據npm
6.取消請求編程
7.自動轉換JSON數據json
8.客戶端支持防止CSRF/XSRF攻擊axios
9.支持promiseAPI後端
axios.defaults.baseURL = 'https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp'; // 默認的路由 axios.interceptors.response.use(result => result.data); //=>設置響應攔截器:分別在響應成功和失敗的時候作一些攔截處理(在執行成功後設定的方法以前,先會執行攔截器中的方法) axios.defaults.validateStatus = function validateStatus(status) { //=>自定義成功失敗規則:RESOLVE / REJECT(默認規則:狀態碼以2開頭算做成功) return /^(2|3)\d{2}$/.test(status); }; //=>設置在POST請求中基於請求主體向服務器發送內容的格式,默認是RAW,項目中經常使用的是URL-ENCODEED格式 axios.defaults.headers['Content-Type'] = 'appliction/x-www-form-urlencoded'; axios.defaults.transformRequest = data => { //=>DATA:就是請求主體中須要傳遞給服務器的內容(對象) let str = ``; for (let attr in data) { if (data.hasOwnProperty(attr)) { str += `${attr}=${data[attr]}&`; } } return str.substring(0, str.length - 1); };
// 寫法一 this.axios({ url: "", // 提交的路由 data: {}, // post請求提交的數據 params: {}, // get請求提交的數據 methods: "", // 請求方式 }).then(function(response) { // 執行成功後執行的回調函數 }).catch(function(response) { // 當then方法拋異常時觸發 }) // 寫法二:直接點出axios中的請求類型的方法 // get請求 axios.get('url',{ data: {}, // post請求提交的數據 params: {}, // get請求提交的數據,顯示在url上 }).then(function(res){ console.log(res);//處理成功的函數 至關於success }).catch(function(error){ console.log(error)// 打印then函數拋的異常 }) // post請求 axios.post('url',{ data: {}, // post請求提交的數據 params: {}, // get請求提交的數據,顯示在url上 }).then(function(res){ console.log(res);//處理成功的函數 至關於success }).catch(function(error){ console.log(error)//打印then函數拋的異常 })
axios.get(url {數據,配置}) axios.delete(url {數據,配置}) axios.head(url {數據,配置}) axios.post(url {數據,配置}) axios.put(url {數據,配置}) axios.patch(url {數據,配置}) // 當使用別名方法時,不須要在config中指定url,method和data屬性
1. `url`是將用於請求的服務器URL url: ‘/user’, 2. `method`是發出請求時使用的請求方法 method: ‘get’, // 默認 3. `baseURL`將被添加到`url`前面,除非`url`是絕對的。 // 能夠方便地爲 axios 的實例設置`baseURL`,以便將相對 URL 傳遞給該實例的方法。 baseURL: ‘https://some-domain.com/api/’, 4. `transformRequest`容許在請求數據發送到服務器以前對其進行更改 // 這隻適用於請求方法’PUT’,’POST’和’PATCH’ // 數組中的最後一個函數必須返回一個字符串,一個 ArrayBuffer或一個 Stream transformRequest: [function (data) { // 作任何你想要的數據轉換 而後 return data; }], 5. `transformResponse`容許在 then / catch以前對響應數據進行更改 transformResponse: [function (data) { // 作任何你想要的數據轉換 而後 return data; }], 6. `headers`是要發送的自定義 headers headers: {‘X-Requested-With’: ’XMLHttpRequest’}, 7. `params`是要與請求一塊兒發送的URL參數 // 必須是純對象或URLSearchParams對象 params: { ID: 12345 }, 8. `paramsSerializer`是一個可選的函數,負責序列化`params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: ’brackets’}) }, 9. `data`是要做爲請求主體發送的數據 // 僅適用於請求方法「PUT」,「POST」和「PATCH」 // 當沒有設置`transformRequest`時,必須是如下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: ’Fred’ }, 10. `timeout`指定請求超時以前的毫秒數。 // 若是請求的時間超過’timeout’,請求將被停止。 timeout: 1000, 11. `withCredentials`指示是否跨站點訪問控制請求 withCredentials: false, // default 12. `adapter’容許自定義處理請求,這使得測試更容易。 // 返回一個promise並提供一個有效的響應(參見[response docs](#response-api)) adapter: function (config) { /* … */ }, 13. `auth’表示應該使用 HTTP 基本認證,並提供憑據。 // 這將設置一個`Authorization’頭,覆蓋任何現有的`Authorization’自定義頭,使用`headers`設置。 auth: { username: ’janedoe’, password: ’s00pers3cret’ }, 14. 「responseType」表示服務器將響應的數據類型 // 包括 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’ responseType: ‘json’, // default 15. `xsrfCookieName`是要用做 xsrf 令牌的值的cookie的名稱 xsrfCookieName: ‘XSRF-TOKEN’, // default 16. `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱 xsrfHeaderName: ‘X-XSRF-TOKEN’, // default 17. `onUploadProgress`容許處理上傳的進度事件 onUploadProgress: function (progressEvent) { // 使用本地 progress 事件作任何你想要作的 }, 18. `onDownloadProgress`容許處理下載的進度事件 onDownloadProgress: function (progressEvent) { }, 19. `maxContentLength`定義容許的http響應內容的最大大小 maxContentLength: 2000, 20. `validateStatus`定義是否解析或拒絕給定的promise // HTTP響應狀態碼。若是`validateStatus`返回`true`(或被設置爲`null` promise將被解析;不然,promise將被 // 拒絕。 validateStatus: function (status) { return status >= 200 && status < 300; // default }, 21. `maxRedirects`定義在node.js中要遵循的重定向的最大數量。 // 若是設置爲0,則不會遵循重定向。 maxRedirects: 5, // 默認 22. `httpAgent`和`httpsAgent`用於定義在node.js中分別執行http和https請求時使用的自定義代理。 // 容許配置相似`keepAlive`的選項, // 默認狀況下不啓用。 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), 23. ‘proxy’定義代理服務器的主機名和端口 // `auth`表示HTTP Basic auth應該用於鏈接到代理,並提供credentials。 // 這將設置一個`Proxy-Authorization` header,覆蓋任何使用`headers`設置的現有的`Proxy-Authorization` 自定義 headers。 proxy: { host: ’127.0.0.1’, port: 9000, auth: : { username: ’mikeymike’, password: ’rapunz3l’ } }, 24. 「cancelToken」指定可用於取消請求的取消令牌 cancelToken: new CancelToken(function (cancel) { }) }
let axiosList = [ this.axios({}), this.axios({}) ] this.axios.all(axiosList).then(axios.spread(function(response1, response2) { // response1, response2分別爲兩個併發執行的axios的回調函數的返回值 })).catch(axios.spread(function(response1, response2) { // response1, response2分別爲兩個併發執行的axios的回調函數then拋的異常 })) // axios是基於promise實現功能的,而promise是一種解決異步編程的方法.想要實現axios併發能夠先將每一個axios事件放在列表中,經過axios內部的all方法實現多個axios事件的併發執行.
export default { name: "Test", data() { return { input: '', msg: '', } }, methods: { submitA() { if (this.input) { // // 回調函數不能直接使用組件中data中的定義的數據.換句話說回調函數獲取的值不能賦值給組件中的data的值 // // 緣由是axios中的this是指代的是Vue,能夠在執行axios以前用一個變量緩存Vue, // // 例如定義一個變量,將Vue指代的this賦值給該變量,在其它地方就可使用該變量代替this let that = this; // this.$axios({ // url: 'http://127.0.0.1:8000/test/', // methods: "get", // // params: { // // input_a: this.input, // // }, // get請求的數據放在request.GET中 // data: { // input_a: this.input, // }, // post請求後端取不到error // }).then(function (response) { // // 回調函數不能直接使用組件中data中的定義的數據.換句話說回調函數獲取的值不能賦值給組件中的data的值 // // 緣由是axios中的this是指代的是Vue,能夠在執行axios以前用一個變量緩存Vue, // // 例如定義一個變量,將Vue指代的this賦值給該變量,在其它地方就可使用該變量代替this // that.msg = response.data.msg; // }).catch(function (error) { // console.log(error) // 打印then函數拋的異常 // }) this.$axios.get( "http://127.0.0.1:8000/test/", { params: {input_a: that.input}, headers:{'Content-Type': 'appliction/x-www-form-urlencoded'}, responseType: 'json', } ).then(function (response) { that.msg = response.data.msg }).catch(function (response) { that.msg = response.data.msg }); } } } }