Axios將帶有自定義頭部的POST 請求發送到某個URL。Axios自動將數據轉換爲JSONios
// axios const options = { url: 'http://localhost/test.htm', method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, data: { a: 10, b: 20 } }; axios(options) .then(response => { console.log(response.status); });
// fetch() const url = 'http://localhost/test.htm'; const options = { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ a: 10, b: 20 }) }; fetch(url, options) .then(response => { console.log(response.status); });
fetch()
使用body屬性,而Axios使用data屬性fetch()
中的數據是字符串化的,JSON.stringify()fetch()
。可是在Axios中,URL是在options對象中設置的Axios在發送請求時自動 stringify 數據(儘管你能夠覆蓋默認行爲並定義不一樣的轉換機制)。可是,在使用 fetch()時,你必須手動完成。對比下:git
// axios axios.get('https://api.github.com/orgs/axios') .then(response => { console.log(response.data); }, error => { console.log(error); }); // fetch() fetch('https://api.github.com/orgs/axios') .then(response => response.json()) // one extra step .then(data => { console.log(data) }) .catch(error => console.error(error));
自動轉換數據是一個很好的特性,但仍是那句話,它不是fetch()作不到的事情。github
在Axios中聲明請求攔截器:json
axios.interceptors.request.use(config => { // log a message before any HTTP request is sent console.log('Request was sent'); return config; }); // sent a GET request axios.get('https://api.github.com/users/sideshowbarker') .then(response => { console.log(response.data); });
在這段代碼中, axios.interceptors.request.use()方法用於定義在發送HTTP請求以前要運行的代碼。axios
要同時發出多個請求,Axios提供了 axios.all()方法。只需將一個請求數組傳遞給這個方法,而後使用axios.spread()將響應數組的屬性分配給多個變量:api
axios.all([ axios.get('https://api.github.com/users/iliakan'), axios.get('https://api.github.com/users/taylorotwell') ]) .then(axios.spread((obj1, obj2) => { // Both requests are now complete console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub'); console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub'); }));