--- tags: Note --- # axios - 支援 Promise API(依賴 ES6 Promise,若不支援請使用 Polyfill) - 可取消請求 (Promise 無法) - 自動轉換 JSON - axios 回傳並非直接是資料,內容包含 data / status / statusText / headers / config ### 好處 1. 統一套用 config.js 2. 統一管理 API,維護延展都較好(分檔案 or import) ### 實作 ###### 下載套件 ``` npm install axios ``` ###### 基本語法 ``` axios(url[,config]) ``` ###### axios 回傳 Promise(fulfilled),所以可以用 `.then` `.catch` 處理成功或失敗結果 ``` const x = axios('https://randomuser.me/api/') x.then((response) => console.log(x)) //Promise {<fulfilled>: {…}} ``` ###### 默認是 `GET` 請求,所以可以這樣寫 ``` axios('https://randomuser.me/api/') .then( (response) => console.log(response)) .catch( (error) => console.log(error)); ``` ###### 但實作比較少這樣寫,通常直接使用 `axios` 的內建方法,`.get` `.post` ``` //GET請求 axios.get('https://randomuser.me/api/') .then( (response) => console.log(response)) .catch( (error) => console.log(error)) //POST請求 axios.post('https://hexschool-tutorial.herokuapp.com/api/signup',{ email: 'javascriptBasics@gmail.com', password: '1234' }) .then( (response) => console.log(response)) .catch( (error) => console.log(error)) ``` --- #### remote img ``` axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream', }) .then((response) => { response.data.pipe(fs.createWriteStream('Img.jpg')) }) ``` --- ## 資料來源 - [axios 基本使用 & Config](https://ithelp.ithome.com.tw/articles/10212120) - [axios中文文档|axios中文网](http://axios-js.com/zh-cn/docs/index.html) - [使用Axios你的API都怎麼管理?](https://medium.com/i-am-mike/%E4%BD%BF%E7%94%A8axios%E6%99%82%E4%BD%A0%E7%9A%84api%E9%83%BD%E6%80%8E%E9%BA%BC%E7%AE%A1%E7%90%86-557d88365619)