Axios

13. Vue-axios基础Get请求

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

  • 从浏览器中创建 XMLHttpRequests

  • 从 node.js 创建 http 请求

  • 支持 Promise API

  • 拦截请求和响应

  • 转换请求数据和响应数据

  • 取消请求

  • 自动转换 JSON 数据

  • 客户端支持防御 XSRF

中文: https://www.kancloud.cn/yunye/axios/234845
github: https/github.com/axios/axios

(1)安装 npm install axios --save

(2)main.js中引入加载

CopyimportAxios form "axios"Vue.prototype.$axios = Axios

(3)请求

Copythis.$axios.get("http://127.0.0.1/add/",{params: {a: "1",b: "2"}})
    .then(res=> {this.result = res.data;})
    .catch(error=> {console.log(error); })

也可使用通用的this.$axios({method:"get", url: '', params: {}, data: {}})

Copythis.$axios({
      method: 'get',
      url: 'https://httpbin.org/get',
      params: {name: '临渊', age: 18, sex: '男'}
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

示例:

src/main.js

Copy// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.importVuefrom'vue'importAxiosfrom'axios'// 导入importAppfrom'./App'Vue.config.productionTip = false// 生产环境配置提示Vue.prototype.$axios = Axios// 挂载到原型的$axios上/* eslint-disable no-new */newVue({
  el: '#app',  // 绑定根视图components: { App },  // 加载组件template: '<App/>'// 使用组件
})

src/App.vue

Copy<template><divid="app">
    {{ data }}
  </div></template><script>exportdefault {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    // this.$axios.get('https://httpbin.org/get?name=临渊&age=18', { params: {sex: '男'} })// .then(res=> { this.data=res.data })// .catch(error=> { console.log(error) })this.$axios({
      method: 'get',
      url: 'https://httpbin.org/get',
      params: {name: '临渊', age: 18, sex: '男'}
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script><stylelang="css"></style>

14. Vue-axios基础Post请求

发送表单格式数据

或使用qs将对象转为urlencoded字符串 (需要导入qs)

Copythis.$axios.post('https://httpbin.org/post', qs.stringify({name: '临渊', age: '18', sex: '男'}))

通用请求方式

Copythis.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: "name=临渊&age=18&sex=男"// 或 qs.stringify({name: '临渊', age: '18', sex: '男'})
    })

示例:

src/main.js

Copy// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.importVuefrom'vue'importAxiosfrom'axios'// 导入importAppfrom'./App'Vue.config.productionTip = false// 生产环境配置提示Vue.prototype.$axios = Axios// 挂载到原型的$axios上/* eslint-disable no-new */newVue({
  el: '#app',  // 绑定根视图components: { App },  // 加载组件template: '<App/>'// 使用组件
})

src/App.vue

Copy<template><divid="app">
    {{ data }}
  </div></template><script>import qs from"qs"exportdefault {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    // this.$axios.post('https://httpbin.org/post', "name=临渊&age=18&sex=男")// this.$axios.post('https://httpbin.org/post', qs.stringify({name: '临渊', age: '18', sex: '男'}))// .then(res=> { this.data=res.data })// .catch(error=> { console.log(error) })this.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: "name=临渊&age=18&sex=男"// 或 qs.stringify({name: '临渊', age: '18', sex: '男'})
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script><stylelang="css"></style>
发送JSON请求
Copythis.$axios.post('https://httpbin.org/post', {name: '临渊', age: '18', sex: '男'})

Copythis.$axios({
      method: 'post',
      url: 'https://httpbin.org/post',
      data: {name: '临渊', age: '18', sex: '男'} 
    })
全局的axios默认值
main.js中, Vue.prototype.$axios = Axios;后
CopyAxios.defaults.baseURL = 'http://127.0.0.1:5000';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Axios.defaults.headers.comont['Authorization'] = AUTH_TOKEN;

15. Vue-axios全局配置与拦截器

全局默认配置

在src/main.js可以添加Axios的全局配置,如

CopyAxios.defaults.baseURL = 'https://httpbin.org';
axios.defaults.headers.common['Authorization'] = '123';
Axios.defaults.headers.post['x-test'] = 'abc';
拦截器

在发送发送请求前或接收响应后执行指定函数。

在src/main.js中添加

  • 拦截请求:Axios.interceptors.request.use(function(config){})

  • 拦截响应:Axios.interceptors.response.use(function(response){})

例如:

Copy// 添加请求拦截器Axios.interceptors.request.use(function(config) {
    if (config.method == "post") {
        config.data = qs.stringify(config.data);  //将所有post对象转为表单格式
    }
    return config;

}, function(error) {
    //对请求错误做些什么returnPromise.reject(error);

});

// 添加响应拦截器Axios.interceptors.response.use(function(response) {
    return response;

}, function(error){
    //对响应错误做点什么returnPromist.reject(error);
}
)

示例:

src/main.js

Copy// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.importVuefrom'vue'importAxiosfrom'axios'// 导入importAppfrom'./App'Vue.config.productionTip = false// 生产环境配置提示Vue.prototype.$axios = Axios// 挂载到原型的$axios上Axios.defaults.baseURL = 'https://httpbin.org';
Axios.defaults.headers.post['x-test'] = 'abc'Axios.interceptors.request.use(function(config){
    console.log(config);
    return config
})

Axios.interceptors.response.use(function(response){
    console.log(response);
    return response
})

/* eslint-disable no-new */newVue({
  el: '#app',  // 绑定根视图components: { App },  // 加载组件template: '<App/>'// 使用组件
})

src/App.vue

Copy<template><divid="app">
    {{ data }}
  </div></template><script>import qs from"qs"exportdefault {
  name: 'App',
  data(){
    return {
      data: {}
    }
  },
  created(){
    this.$axios({
      method: 'post',
      url: '/post',
      data: 'name=临渊&age=18' 
    })
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })

  }
}
</script><stylelang="css"></style>

16. Vue-axios跨域处理

调试时如何使用数据

使用mock模拟数据
  1. 自己创建JSON文件, 使用get请求形式访问数据

  1. 优点: 方便,快捷

  1. 缺点: 只能存在get请求

  1. 项目中集成服务器, 模拟各种接口

  1. 优点: 模拟真实线上环境

  1. 缺点: 增加开发成本

  1. 直接使用线上数据

  1. 优点: 使用

  1. 不一定每个项目都存在

使用后端接口

如使用Axios直接请求

Copycreated(){
    this.$axios.get('http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0')
    .then(res=> { this.data=res.data })
    .catch(error=> { console.log(error) })
  }

Chrome Console面板会报跨域错误,如下:

CopyAccessto XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

需要解决跨域问题,解决方式,使用Nodejs后端服务作为请求中转来解决跨域问题,方式如下:

  1. 修改config/index.js文件dev端的proxyTable(只对开发环境生效),添加api配置,并重启(修改配置后需要重启才能生效)

Copy// 解决跨域问题proxyTable:{
        "/api": {
            target: "http://tingapi.ting.baidu.com",
            changeOrigin: true,
            pathRewrite: {
                "^/api": ""
            }
        }
    },
  1. src/main.js中读取配置并绑定到原型的HOST属性上
    Vue.prototype.HOST = '/api';

  1. 组件中重新组装url
    var url = this.HOST + "v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0";

示例:

config/index.js

Copy...
module.exports = {
  dev: {
    ...
    proxyTable: {
        '/api': {
            target: "http://tingapi.ting.baidu.com",
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
    ...

src/main.js

CopyimportVuefrom'vue'importAxiosfrom'axios'// 导入AxiosimportAppfrom'./App'Vue.config.productionTip = false// 生产环境配置提示Vue.prototype.$axios = Axios// 挂载到原型的$axios上Vue.prototype.HOST = {baiduting: '/api'}  // 支持绑定多个newVue({
  el: '#app',  // 绑定根视图components: { App },  // 加载组件template: '<App/>'// 使用组件
})

src/App.vue

Copy<template><divid="app"><h2>最火歌曲</h2><ul><liv-for="(item,index) in songList">{{ index + 1 }}. {{ item.author }} - {{ item.title }}</li></ul></div></template><script>import qs from"qs"exportdefault {
  name: 'App',
  data(){
    return {
      songList: []
    }
  },
  created(){
    var url = this.HOST.baiduting + '/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0'this.$axios.get(url)
    .then(res=> { this.songList=res.data.song_list })
    .catch(error=> { console.log(error) })
  }
}
</script><stylelang="css"></style>

17. Vue操作原始DOM

Vue直接操作原始DOM(不推荐)
  • template中节点使用ref="名称"绑定

  • scripts中使用this.$refs.名称来引用节点

示例:

src/App.vue

Copy<template><divid="app"><pref="myp">哈哈</p></div></template><script>exportdefault {
  name: 'App',
  data(){
    return {
    }
  },
  mounted(){
    console.log(this.$refs.myp.innerHTML='嘿嘿');
    console.log(this.$refs.myp.style.color='red');
    this.$refs.myp.addEventListener("click", function(){console.log('clicked');})  // 添加时间
  }
}
</script><stylelang="css"></style>
使用jQuery操作DOM

(1)安装jQuery cnpm install --save jquery,重启项目

(2)组件中引入jQuery import $ from "jquery"

(3)组件中使用 $('#myp').css("color", "red")

示例:

src/App.vue

Copy<template><divid="app"><pid="myp">哈哈</p></div></template><script>import $ from"jquery"exportdefault {
  name: 'App',
  data(){
    return {
    }
  },
  mounted(){
    $('#myp').css("color", "red");
  }
}
</script><stylelang="css"></style>

如有不懂还要咨询下方小卡片,博主也希望和志同道合的测试人员一起学习进步

在适当的年龄,选择适当的岗位,尽量去发挥好自己的优势。

我的自动化测试开发之路,一路走来都离不每个阶段的计划,因为自己喜欢规划和总结,

测试开发视频教程、学习笔记领取传送门!!!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐