在以前的项目中使用了Promise对数据进行请求,但是在使用过程中有的数据会请求不到,这次采用封装过的axios进行数据交互
axios能做什么?
- 支持XMLHTTPRequest
- 支持promise
- 支持CSRF
一,在vue中安装axios
npm install axios --save
当然对于传统页面可以通过<script></script>标签引用axios的文件
二、配置axios到全局环境
在vue项目中找到main.js文件,这个就是vue项目的js入口文件,在里面添加对axios的引用:
import axios from 'axios'
Vue.prototype.$axios = axios
然后在对应的页面使用
this.$axios.post('/url',{
param1:this.message,
param2:this.note
})
.then(function(response){
alert("您的请求已提交!谢谢");
})
.catch(function(error){
alert("由于网络故障,请求提交失败!请您稍后再试");
})
this.$axios.get('https:www.baidu.com')
.then(function(response){
console.log("response:"+response);
})
.catch(function(error){
console.log("error:"+error);
})
配置方法二
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
//使用方法
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
this.axios.get(api).then((response) => {
console.log(response.data)
})
this.$http.get(api).then((response) => {
console.log(response.data)
})
然后再打开网页就可以实现请求。