Vue之axios

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26641781/article/details/83867545

axios 简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:


 1. 从浏览器中创建 XMLHttpRequest
 2. 从 node.js 发出 http 请求从 node.js 发出 http 请求
 3. 支持 Promise API支持 Promise API
 4. 拦截请求和响应拦截请求和响应
 5. 转换请求和响应数据转换请求和响应数据
 6. 取消请求取消请求
 7. 自动转换JSON数据
 8. 客户端支持防止 CSRF/XSRF客户端支持防止 CSRF/XSRF

引入方式:

$ npm install axios
$ cnpm install axios //taobao源
$ bower install axios
或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

例子:
main.js注册axios

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$axios = axios

new Vue({
  router,
  store,
  axios,
  render: h => h(App)
}).$mount('#app')

axios之get请求

getApi(){
      this.$axios.get("url")
      .then((res) => {
        console.log('111')
        console.log(res.data)
      })
      .catach((err) => {
        console.log('222')
        console.log(err)
      })
 

axios之post请求

axios.post('url', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

执行多个并发请求

function getUserAccount() {
return axios.get('url1');
}
 
function getUserPermissions() {
return axios.get('url2');
}
 
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
//两个请求现已完成
}));

猜你喜欢

转载自blog.csdn.net/qq_26641781/article/details/83867545