1 https://github.com/axios/axios 2 axios API 3 為方便起見,為所有支持的請求方法提供了別名,在使用別名方法時, url、method、data 這些屬性都不必在配置中指定。 4 5 axios.request(config) 6 axios.get(url[, config]) 7 axios.delete(url[, config]) 8 axios.head(url[, config]) 9 axios.post(url[, data[, config]]) 10 axios.put(url[, data[, config]]) 11 axios.patch(url[, data[, config]]) 12 13 並發 14 axios.all(iterable) 15 axios.spread(callback) 16 17 創建實例 18 const instance = axios.create([config]) 19 20 21 實例方法,,以下是可用的實例方法。指定的配置將與實例的配置合並 22 axios#request(config) 23 axios#get(url[, config]) 24 axios#delete(url[, config]) 25 axios#head(url[, config]) 26 axios#post(url[, data[, config]]) 27 axios#put(url[, data[, config]]) 28 axios#patch(url[, data[, config]]) 29 instance({config}) 30 31 這些是創建請求時可以用的配置選項。只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。 32 { 33 // 是用於請求的服務器 URL 34 url:'', 35 //是創建請求時使用的方法,默認是 get 36 method:'', 37 // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL 38 baseURL:'', 39 // `transformRequest` 允許在向服務器發送前,修改請求數據,只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 40 // // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream 41 transformRequest:[function(data,headers){ 42 // 對 data 進行任意轉換處理 43 return data; 44 }], 45 // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 46 transformResponse:[function(data){ 47 48 return data; 49 }], 50 // `headers` 是即將被發送的自定義請求頭 51 headers: { 52 'X-Requested-With': 'XMLHttpRequest' 53 }, 54 // `params` 是即將與請求一起發送的 URL 參數 55 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 56 params: { 57 ID: 12345 58 }, 59 // `paramsSerializer` 是一個負責 `params` 序列化的函數 60 paramsSerializer: function (params) { 61 return Qs.stringify(params, {arrayFormat: 'brackets'}) 62 }, 63 // `data` 是作為請求主體被發送的數據 64 // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH' 65 // 在沒有設置 `transformRequest` 時,必須是以下類型之一: 66 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 67 // - 瀏覽器專屬:FormData, File, Blob 68 // - Node 專屬: Stream 69 data: { 70 firstName: 'Fred' 71 }, 72 // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) 73 // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 74 timeout: 1000, 75 76 // `withCredentials` 表示跨域請求時是否需要使用憑證 77 withCredentials: false, // 默認的 78 79 80 // `adapter` 允許自定義處理請求,以使測試更輕松 81 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). 82 adapter: function (config) { 83 . 84 }, 85 // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 86 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 87 //請注意,只能通過此參數配置HTTP Basic身份驗證。 88 //對於Bearer令牌等,請改用`Authorization`自定義標頭。 89 auth: { 90 username: 'janedoe', 91 password: 's00pers3cret' 92 }, 93 // `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' 94 responseType: 'json', // 默認的 95 96 // `responseEncoding`表示用於解碼響應的編碼 97 // 注意:忽略“ stream”或客戶端請求的“ responseType” 98 responseEncoding: 'utf8', // 默認的 99 100 // xsrfCookieName是cookie的名稱,用作xsrf令牌的值 101 xsrfCookieName: 'XSRF-TOKEN', // default 102 103 // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 104 xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的 105 106 // `onUploadProgress` 允許為上傳處理進度事件 107 onUploadProgress: function (progressEvent) { 108 // 對原生進度事件的處理 109 }, 110 111 // `onDownloadProgress` 允許為下載處理進度事件 112 onDownloadProgress: function (progressEvent) { 113 // 對原生進度事件的處理 114 }, 115 // `maxContentLength` 定義允許的響應內容的最大尺寸 116 maxContentLength: 2000, 117 118 // // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。 119 // 如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte 120 validateStatus: function (status) { 121 return status >= 200 && status < 300; // 默認的 122 }, 123 // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 124 // 如果設置為0,將不會 follow 任何重定向 125 maxRedirects: 5, // 默認的 126 127 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項: 128 // `keepAlive` 默認沒有啟用 129 130 httpAgent: new http.Agent({ keepAlive: true }), 131 httpsAgent: new https.Agent({ keepAlive: true }), 132 133 // 'proxy' 定義代理服務器的主機名稱和端口 134 // `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據 135 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 136 proxy: { 137 host: '127.0.0.1', 138 port: 9000, 139 auth: : { 140 username: 'mikeymike', 141 password: 'rapunz3l' 142 } 143 }, 144 } 145 146 // 響應結構 147 { 148 // `data` 由服務器提供的響應 149 data: {}, 150 // `status` 來自服務器響應的 HTTP 狀態碼 151 status: 200, 152 // `statusText` 來自服務器響應的 HTTP 狀態信息 153 statusText: 'OK', 154 // `headers` 服務器響應的頭 155 headers: {}, 156 // `config` 是為請求提供的配置信息 157 config: {} 158 } 159 160 全局的 axios 默認值 161 axios.defaults.baseURL = 'https://api.example.com'; 162 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 163 164 自定義實例默認值 165 // 創建實例時設置配置的默認值 166 var instance = axios.create({ 167 baseURL: 'https://api.example.com' 168 }); 169 170 // 在實例已創建后修改默認值 171 axios.defaults.baseURL = 'https://api.example.com'; 172 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 173 174 配置的優先順序 175 var instance = axios.create(); 176 177 instance.defaults.timeout = 2500; 178 179 instance.get('/longRequest', { 180 timeout: 5000 181 }); 182 183 184 攔截器 185 在請求或響應被 then 或 catch 處理前攔截它們。 186 187 // 添加請求攔截器 188 axios.interceptors.request.use(function (config) { 189 // 在發送請求之前做些什么 190 return config; 191 }, function (error) { 192 // 對請求錯誤做些什么 193 return Promise.reject(error); 194 }); 195 196 // 添加響應攔截器 197 axios.interceptors.response.use(function (response) { 198 // 對響應數據做點什么 199 return response; 200 }, function (error) { 201 // 對響應錯誤做點什么 202 return Promise.reject(error); 203 }); 204 205 如果你想在稍后移除攔截器,可以這樣: 206 var myInterceptor = axios.interceptors.request.use(function () { ....}); 207 axios.interceptors.request.eject(myInterceptor); 208 209 210 可以為自定義 axios 實例添加攔截器 211 var instance = axios.create(); 212 instance.interceptors.request.use(function () {.../}); 213 214 215 執行多個並發請求 216 function getUserAccount() { 217 return axios.get('/user/12345'); 218 } 219 function getUserPermissions() { 220 return axios.get('/user/12345/permissions'); 221 } 222 axios.all([getUserAccount(), getUserPermissions()]) 223 .then(axios.spread(function (acct, perms) { 224 // 兩個請求現在都執行完成 225 })); 226 227 // 取消請求 228 方法一: 229 var CancelToken = axios.CancelToken; 230 var source = CancelToken.source(); 231 232 axios.get('/user/12345', { 233 cancelToken: source.token 234 }).catch(function(thrown) { 235 if (axios.isCancel(thrown)) { 236 console.log('Request canceled', thrown.message); 237 } else { 238 // 處理錯誤 239 } 240 }); 241 242 // 取消請求(message 參數是可選的) 243 source.cancel('Operation canceled by the user.'); 244 245 246 方法二: 247 var CancelToken = axios.CancelToken; 248 var cancel; 249 250 axios.get('/user/12345', { 251 cancelToken: new CancelToken(function executor(c) { 252 // executor 函數接收一個 cancel 函數作為參數 253 cancel = c; 254 }) 255 }); 256 // 取消請求 257 cancel();