vue axios代替ajax發送http請求

一、GET

<div id="app">
  <h1>網站列表</h1>
  <div
    v-for="site in info"
  >
    {{ site.name }}
  </div>
</div>
<script type = "text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch(function (error) { // 請求失敗處理
        console.log(error);
      });
  }
})
</script>
//兩種傳參方式
// 直接在 URL 上添加參數 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也可以通過 params 設置參數:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

二、post

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .post('https://www.runoob.com/try/ajax/demo_axios_post.php')
      .then(response => (this.info = response))
      .catch(function (error) { // 請求失敗處理
        console.log(error);
      });
  }
})
//傳參
axios.post('/user', {
    firstName: 'Fred',        // 參數 firstName
    lastName: 'Flintstone'    // 參數 lastName
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

三、攔截器

// 添加請求攔截器
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)
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章