基本語法json
//基於全局Vue對象使用http Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); //在一個Vue實例內使用$http this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
7種請求API跨域
options對象服務器
參數app |
類型cors |
描述ide |
url函數 |
stringpost |
請求的 URLjsonp |
methodthis |
string |
請求的 HTTP 方法,例如:'GET','POST' 或其餘 HTTP 方法 |
body |
Object, FormData string |
request body |
params |
Object |
請求的 URL 參數對象 |
headers |
Object |
request header |
timeout |
number |
單位爲毫秒的請求超時時間 (0 表示無超時時間) |
before |
function(request) |
請求發送前的處理函數,相似於 jQuery 的 beforeSend 函數 |
progress |
function(event) |
ProgressEvent 回調處理函數 |
credentials |
boolean |
表示跨域請求時是否須要使用憑證(可用於解決 cors 跨域請求沒帶上 Cookie 的問題) |
emulateHTTP |
boolean |
發送 PUT,PATCH,DELETE 請求時以 HTTP POST 的方式發送,並設置請求頭的 X-HTTP-Method-Override |
emulateJSON |
boolean |
將 request body 以 content-type 爲 application/x-www-form-urlencoded 的方式發送 |
emulateHTTP 的做用
若是Web服務器沒法處理 PUT、PATCH 和 DELETE 這種 REST 風格的請求,你能夠啓用 enulateHTTP 現象。啓用該選項後,請求會以普通的 POST 方法發出,而且 HTTP 頭信息的 X-HTTP-Method-Override 屬性會設置爲實際的 HTTP 方法。
Vue.http.options.emulateHTTP = true;
emulateJSON的做用
若是 Web 服務器沒法處理編碼爲 application/json 的請求,你能夠啓用 emulateJSON 選項。啓用該選項後,請求會以 application/x-www-form-urlencoded 做爲 MIME type,就像普通的 HTML 表單同樣。
Vue.http.options.emulateJSON = true;
response 對象
方法 |
類型 |
描述 |
text() |
string |
以 string 形式返回 response body |
json() |
Object |
以 JSON 對象形式返回 response body |
blob() |
Blob |
以二進制形式返回 response body |
屬性 |
類型 |
描述 |
ok |
boolean |
響應的 HTTP 狀態碼在 200~299 之間時,該屬性爲 true |
status |
number |
響應的 HTTP 狀態碼 |
statusText |
string |
響應的狀態文本 |
headers |
Object |
響應頭 |
全局配置
Vue.http.options.emulateHTTP = true;
Vue.http.options.emulateJSON = true;
Vue.http.interceptors.push(function (request, next) { // ... // 請求發送前的處理邏輯 // ... next(function (response) { // ... // 請求發送後的處理邏輯 // ... // 根據請求的狀態,response 參數會返回給 successCallback 或 errorCallback return response; }); });
上面的配置會對全部請求生效