axios的特点:
1. axios用于封装底层的XMLHttpRequest。
2. 基于promise机制,可以使用承诺对象中的方法(then,catch,finally)。
3. axios会对响应结果做二次封装。
axios中的post方式:
默认发送的是json字符串,也就是请求头的默认格式为:contentType:“application/json”。
问题:如何给后台发送查询字符串格式的数据?
将对象转换为查询字符串:Qs.stringify(obj)
ajax中的post方式:
默认发送的是查询字符串,也就是说请求头的默认格式为:contentType:“application/x-www-form-urlencoded”。
问题:如何给后台发送json字符串格式的数据?
将对象转换成json字符串: JSON.stringify(obj)
axios 请求方式传递参数格式:
axios.get(url[, config])
axios.post(url[, data[, config]])
例子:
1.cdn在线引入插件
1 2 3 | <script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script> <script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.min.js"></script> <script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script> |
2.给button绑定事件
1 2 3 4 5 6 7 | <div id="app"> <div>{<!-- -->{<!-- -->response}}</div> <button @click='findAllCustomers'>查询所有用户信息</button> <button @click='findCustomerById'>根据id获取顾客信息</button> <button @click='login'>登录</button> <button @click='queryCustomers'>分页查询顾客信息</button> </div> |
3.在对应事件内向后台家政接口发送请求
1 2 3 4 5 6 7 8 9 10 | <script> new Vue({<!-- --> el: '#app', data: {<!-- --> response: [] }, methods: {<!-- --> //发送请求 } </script> |
4.查询所有顾客信息: get-无参
1 2 3 4 5 6 7 8 9 10 11 | findAllCustomers() {<!-- --> // console.log(1) axios({<!-- --> url: 'http://公网IP:5588/customer/findAll', method: 'get', }).then((res) => {<!-- --> console.log(res.data.data) }) } |
简写形式:
1 2 3 4 5 | axios.get('http://公网IP:5588/customer/findAll') .then((res) => {<!-- --> console.log(res.data.data) }) |
- get-有参
1 2 3 4 5 6 7 8 9 10 11 | findCustomerById() {<!-- --> let baseURL = 'http://公网IP:5588/' axios({<!-- --> url: baseURL + 'customer/findCustomerById', method: 'get', params: {<!-- --> id: 134 } }).then(res => {<!-- --> console.log(res.data.data) this.response = res.data.data }) } |
简写形式:
1 2 3 4 5 | axios.get(baseURL + 'customer/findCustomerById', {<!-- --> params: {<!-- --> id: 134 } }) .then(res => {<!-- --> console.log(res.data.data) this.response = res.data.data }) |
- post-json格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | login() {<!-- --> let obj = {<!-- --> password: 123321, type: 'customer', username: 'susan' } axios({<!-- --> url: 'http://公网IP:5588/user/login', method: 'post', data: obj }).then((res) => {<!-- --> console.log(res.data.data) }) } |
简写格式:
1 2 3 | axios.post('http://公网IP:5588/user/login', obj).then((res) => {<!-- --> console.log(res.data.data) }) |
7.post-qs格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 | queryCustomers() {<!-- --> let obj = {<!-- --> page: 0, pageSize: 10 } axios({<!-- --> url: 'http://公网IP:5588/customer/query', method: 'post', data: Qs.stringify(obj) }).then((res) => {<!-- --> console.log(res.data.data.list) }) } |
简写格式:
1 2 3 4 | axios.post('http://公网IP:5588/customer/query', Qs.stringify(obj)) .then((res) => {<!-- --> console.log(res.data.data.list) }) |