vue使用Axios做ajax請求詳解,vueaxiosajax詳解

來源:互聯網
上載者:User

vue使用Axios做ajax請求詳解,vueaxiosajax詳解

vue2.0之後,就不再對vue-resource更新,而是推薦使用axios

1. 安裝 axios

$ npm install axios

$ bower install axios

2. 在要使用的檔案中引入axios

import axios from 'axios'

3. 使用axios做請求

可以通過向 axios 傳遞相關配置來建立請求, 只有 url 是必需的。如果沒有指定 method,請求將預設使用 get 方法。

{ // `url` 是用於請求的伺服器 URL url: '/user', // `method` 是建立請求時使用的方法 method: 'get', // 預設是 get // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設定一個 `baseURL` 便於為 axios 執行個體的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允許在向伺服器發送前,修改請求資料 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個要求方法 // 後面數組中的函數必須返回一個字串,或 ArrayBuffer,或 Stream transformRequest: [function (data) {  // 對 data 進行任意轉換處理  return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應資料 transformResponse: [function (data) {  // 對 data 進行任意轉換處理  return data; }], // `headers` 是即將被發送的自訂要求標頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一起發送的 URL 參數 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 params: {  ID: 12345 }, // `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'}) }, // `data` 是作為請求主體被發送的資料 // 只適用於這些要求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設定 `transformRequest` 時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: {  firstName: 'Fred' }, // `timeout` 指定請求逾時的毫秒數(0 表示無逾時時間) // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // 預設的 // `adapter` 允許自訂處理請求,以使測試更輕鬆 // 返回一個 promise 並應用一個有效響應 (查閱 [response docs](#response-api)). adapter: function (config) {  /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設定一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設定的自訂 `Authorization`頭 auth: {  username: 'janedoe',  password: 's00pers3cret' }, // `responseType` 表示伺服器響應的資料類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 預設的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // 預設的 // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) {  // 對原生進度事件的處理 }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) {  // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態代碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設定為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) {  return status >= 200 && status < 300; // 預設的 }, // `maxRedirects` 定義在 node.js 中 follow 的最大重新導向數目 // 如果設定為0,將不會 follow 任何重新導向 maxRedirects: 5, // 預設的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自訂代理。允許像這樣配置選項: // `keepAlive` 預設沒有啟用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義Proxy 伺服器的主機名稱和連接埠 // `auth` 表示 HTTP 基礎驗證應當用於串連代理,並提供憑據 // 這將會設定一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設定的自訂 `Proxy-Authorization` 頭。 proxy: {  host: '127.0.0.1',  port: 9000,  auth: : {   username: 'mikeymike',   password: 'rapunz3l'  } }, // `cancelToken` 指定用於取消請求的 cancel token cancelToken: new CancelToken(function (cancel) { })}

為方便,所有支援的要求方法都提供了別名:

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

4. 請求的響應結構

{ // `data` 由伺服器提供的響應 data: {}, // `status` 來自伺服器響應的 HTTP 狀態代碼 status: 200, // `statusText` 來自伺服器響應的 HTTP 狀態資訊 statusText: 'OK', // `headers` 伺服器響應的頭 headers: {}, // `config` 是為請求提供的配置資訊 config: {}}

使用 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); });

在使用 catch 時,響應可以通過 error 對象可被使用

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

5. 使用執行個體

el1: get請求

axios.get('/user', {  params: {   ID: 12345  } }) .then(function (response) {  console.log(response); }) .catch(function (error) {  console.log(error); });

el2: post請求

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

el3: 執行多個並發請求

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) {  // 兩個請求現在都執行完成 }));

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.