axios post 傳遞陣列_axios 上手指南
技術標籤:axios post 傳遞陣列
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
1 - 功能
- 從瀏覽器中建立 XMLHttpRequests
- 從 node.js 建立 http 請求
- 支援 Promise API
- 攔截請求和響應
- 轉換請求資料和響應資料
- 取消請求
- 自動轉換 JSON 資料
- 客戶端支援防禦 XSRF
2 - 安裝
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
3 - 例子
3.1 GET
axios.get('/user?ID=123') .then( res => { // 請求資料成功並返回資料 console.info(res) }).catch( e => { if (e.response) { // 請求已發出,伺服器返回狀態碼不是 2xx console.info(e.response.data) console.info(e.response.status) console.info(e.response.headers) } else if (e.request) { // 請求已發出,但沒有收到響應 // e.request 在瀏覽器裡是一個 XMLHttpRequest 例項 // 在 node 中是一個 http.ClientRequest 例項 console.info(e.request) } else { // 傳送請求時異常,捕獲到錯誤 console.info('error', e.message) } console.info(e.config) }) // 等同於以下寫法 axios({ url: '/user', methods: 'GET', params: { ID: 123 } }).then(res => { console.info(res) }).catch(e => { console.info(e) }) // 為給定 ID 的 user 建立請求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 可選地,上面的請求可以這樣做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3.2 POST
axios.post('/user', { firstName: 'Mike', lastName: 'Allen' }).then(res => { console.info(res) }).catch(e => { console.info(e) }) // 等同於以下寫法 axios({ url: '/user', method: 'POST', data: { firstName: 'Mike', lastName: 'Allen' } }).then(res => { console.info(res) }).catch(e => { console.info(e) }) axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3.3 執行多個併發請求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermission()])
.then(axios.spread(function (acct, perms) {
// 兩個請求現在都執行完成
}));
3.4 注意事項
在使用 GET
方法傳遞引數時使用的是 params
,並且官方文件中介紹:
params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object.
params
作為 URL 連結中的引數傳送請求,且其必須是一個 plain object
或者是 URLSearchParams object
。
plain object
(純物件):是指JSON
形式定義的普通物件或者new Object()
建立的簡單物件;URLSearchParams object
:指的是一個可以由 URLSearchParams 介面定義的一些實用方法來處理 URL 的查詢字串的物件,也就是說params
傳參是以/user?ID=1&name=mike&sex=male
形式傳遞的。
而在使用 POST
時對應的傳參使用的是 data
,data
是作為 請求體 傳送的,同樣使用這種形式的還有 PUT
、PATCH
等請求方法。有一點需要注意的是,axios
中 POST
的預設請求體型別為 Content-Type:application/json
(JSON 規範流行),這也是最常見的請求體型別,也就是說使用的是序列化後的 json
格式字串來傳遞引數,如: { "name" : "mike", "sex" : "male" }
;同時,後臺必須要以支援 @RequestBody
的形式來接收引數,否則會出現前臺傳參正確,後臺不接收的情況。
如果想要設定型別為 Content-Type:application/x-www-form-urlencoded
(瀏覽器原生支援),axios
提供了兩種方式,如下:
瀏覽器端
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/user', params);
不過,並不是所有瀏覽器都支援 URLSearchParams
,相容性查詢caniuse.com,但是這裡有一個Polyfill(polyfill
:用於實現瀏覽器並不支援的原生 API 的程式碼,可以模糊理解為補丁,同時要確保 polyfill
在全域性環境中)。
或者,你也可以用 qs
這個庫來格式化資料,預設情況下在安裝完 axios
後就可以使用 qs
庫。
const qs = require('qs');
axios.post('/user', qs.stringify({'name': 'mike'}));
node 層
在 node
環境中可以使用 querystring
。同樣,也可以使用 qs
來格式化資料。
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({'name':'mike'}));
3.5 補充
常見的請求體型別還有一種方式,即multipart/form-data
(瀏覽器原生支援),也就是提交表單資料常用的一種格式。和x-www-form-urlencoded
對比起來,後者則是資料被編碼成以 '&' 分隔的鍵-值對, 同時以 '=' 分隔鍵和值。非字母或數字的字元會被Percent-encoding(URL encoding),這也就是為什麼這種型別不支援二進位制資料的原因 (應使用 multipart/form-data 代替)。
4 - axios API
4.1 請求方法的別名
為了方便起見,axios
提供了別名:
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])
在使用別名方法時,url
、methods
、data
這些屬性都不必在配置中指定。
4.2 併發
處理併發請求的助手函式
axios.all(iterable)
axios.spread(callback)
4.3 建立例項
可以使用自定義配置新建一個 axios
例項
axios.create([config])
var instance = axios.create({
baseURL: 'https://something.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})
4.4 例項方法
以下是可用的例項方法,指定的配置將與例項的配置合併。
- 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]])
5 - 請求配置
這些是建立請求時可以使用的配置選項。只有 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' 定義代理伺服器的主機名稱和埠
// `auth` 表示 HTTP 基礎驗證應當用於連線代理,並提供憑據
// 這將會設定一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設定的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用於取消請求的 cancel token
// (檢視後面的 Cancellation 這節瞭解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
6 - 響應結構
某個請求的響應包含以下資訊:
{
// `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
時,或傳遞 rejection callback 作為 then
的第二個引數時,響應可以通過 error
物件可被使用,正如在錯誤處理這一節所講。
7 - 配置的預設值/defaults
你可以指定將別用在各個請求的配置預設值
7.1 全域性的 axios 預設值
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';
7.2 自定義例項預設值
// 建立例項時設定配置的預設值
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// 在例項已建立後修改預設值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
7.3 配置的優先順序
配置會以一個優先順序進行合併。這個順序是:在 lib/defaults.js
找到的庫的預設值,然後是例項的 defaults
屬性,最後是請求的 config
引數。後者將優先於前者。這裡是一個例子:
// 使用由庫提供的配置的預設值來建立例項
// 此時超時配置的預設值是 `0`
var instance = axios.create();
// 覆寫庫的超時預設值
// 現在,在超時前,所有請求都會等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費很長時間的請求覆寫超時設定
instance.get('/longRequest', {
timeout: 5000
});
8 - 攔截器
在請求或響應被 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);
});
如果你想在稍後移除攔截器,可以這樣:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
可以為自定義 axios 例項新增攔截器:
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
9 - 錯誤處理
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 時才會 reject
}
})
10 - 取消
使用 cancel token
取消請求
Axios 的 cancel token API 基於 cancelable promises proposal,它還處於第一階段。
可以使用 CancelToken.source
工廠方法建立 cancel token
,像這樣:
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 處理錯誤
}
});
// 取消請求(message 引數是可選的)
source.cancel('Operation canceled by the user.');
還可以通過傳遞一個 executor
函式到 CancelToken
的建構函式來建立 cancel token
:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函式接收一個 cancel 函式作為引數
cancel = c;
})
});
// 取消請求
cancel();
Note:可以使用同一個
cancel token
取消多個請求。