--- tags: Javascript, Frontend --- # axios基本語法 ## 簡介 axios是一種HTTP的請求工具,也是Vue的作者尤雨溪推薦使用,比起ajax更為輕量,跟fetch一樣使用promise物件,卻不限至瀏覽器,只需要短短幾行程式碼即可,寫法更加直覺,以下為官方表明特點。 1. 從瀏覽器發出 XMLHttpRequests 1. 可以從 node.js 發出 http 請求 1. 支持 Promise API 1. 攔截請求和響應 1. 轉換請求和響應數據 1. 取消請求 1. JSON 數據的自動轉換 1. 客戶端支持防止 XSRF ## 安裝 介紹常見的安裝方式,其他請查閱文檔 ### 使用NPM `$ npm install axios` ### 引入CDN `<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>` ## axios基本用法 ### axios get方法 沒有參數時get請求 ```javascript= axios.get('https://example.com') // 放入要發出get請求網址 .then(function (response) { // 當請求成功時 console.log(response); }) .catch(function (error) { // 請求失敗時 console.log(error); }) .then(function () { // 總是執行 }); ``` 有參數 ```javascript= axios.get('https://example.com', { params: { ID: 123 } }) // 幫你組合成https://example.com?ID=123 .then(function (response) { // 當請求成功時 console.log(response); }) .catch(function (error) { // 請求失敗時 console.log(error); }) .then(function () { // 總是執行 }); ``` ### axios post方法 使用post請求,傳送name和eamil資料 ```javascript= axios.post('/signup', { name: 'Joe', email: 'joe94113@gmail.com' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 當然除了get,post之外還有其他HTTP請求可以使用,使用方式也是大同小異,就是路由以及HTTP method的改變而已。 ## 使用六角註冊登入API axios範例程式碼 <iframe height="300" style="width: 100%;" scrolling="no" title="CodePen Home Hexschool AJAX POST 小節作業" src="https://codepen.io/joe94113/embed/YzrPjEQ?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/joe94113/pen/YzrPjEQ"> CodePen Home Hexschool AJAX POST 小節作業</a> by 王冠智 (<a href="https://codepen.io/joe94113">@joe94113</a>) on <a href="https://codepen.io">CodePen</a>. </iframe>