一、簡介
1、axios是基於Promise,用於瀏覽器(script標籤引入)和nodejs的,與服務端進行通信的庫
2、特徵:
- 支持Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- 自動轉換JSON數據
3、使用 - CDN地址:https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js
- node npm install axios --save-dev
二、使用
1、在需要的模塊中引入使用:
import axios from 'axios'
2、語法:
- axios( config )
- axios[ method ]()
- 返回值爲promise,意味着可以接着在後面使用then捕獲到成功,catch捕獲到error
3、支持的請求方式 - axios.get( url[ ,config ] )
- axios.post( url[ ,data[ ,config ] ] )
- axios.delete( url[ ,config ] )
- axios.head( url[ ,config ] )
- axios.options( url[ ,config ] )
- axios.put( url[ ,data[ ,config ] ] )
- axios.patch( url[ ,data[ ,config ] ] )
4、axios在created(){}裏面使用,寫在具體組件內,比如table.vue
5、通過get方式向後端發送數據,數據是寫在地址欄?後面的
三、案例
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
created(){
/*axios.get('https://www.easy-mock.com/mock/5c1767c06ccaa7461ef01ee9/example/dataList',{
params:{
name:'xiao',
age:'20'
}
})
.then((response)=>{
console.log(response.data)
})
.catch((error)=>{
console.log(error)
})*/
//發送給後端的數據附在url的?後面
//Request URL:https://www.easy-mock.com/mock/5c1767c06ccaa7461ef01ee9/example/dataList?name=xiao
axios.post('https://www.easy-mock.com/mock/5c1767c06ccaa7461ef01ee9/example/postData',{
name:'xiao'
})
.then((response)=>{
console.log(response.data)
})
.catch((error)=>{
console.log(error)
})
}
}
////數據是隱藏的,不會顯示出來,放在Request Payload {name:'xiao'}
</script>